Skip to content

Chapter 3: Copy and Move Operations - A compiler-generated copy constructor #3

@glucu

Description

@glucu

NOTE: If anyone can correct me or agree with my finding, please state it here. :)

The book states: The compiler will generate an implicit copy constructor for you if your class complies with the following key rules:

  • Your class doesn't have a user-defined copy assignment operator and a user-defined destructor.

However, cppreference states:

  • The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

Here is an example of a simple generated code with C++ Insights: (In which case the compiler does not mark the copy constructor as deleted).


#include <iostream>
#include <memory>
#include <string>

class Foo
{
  
  public: 
  inline constexpr Foo() noexcept = default;
  inline Foo & operator=(const Foo & rhs)
  {
    if(this == &rhs) {
      return *this;
    } 
    
    this->m_s.operator=(rhs.m_s);
    this->m_i = rhs.m_i;
    return *this;
  }
  
  
  private: 
  std::basic_string<char> m_s;
  int m_i;
  public: 
  // inline ~Foo() noexcept = default;
};

int main()
{
  Foo foo = Foo{};
  return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions