Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 11: is a defaulted copy constructor user declared?

Tags:

c++

c++11

I guess it is so, but I am looking for C++11 language lawyers to confirm my impression. Is it true that the following class

struct X{
X(){}
X(X const&)=default;
};

will not be automatically move-enabled, i.e., getting X(X&&) and operator=(X&&), because its copy constructor is "user-declared", even though it looks equivalent to

struct X{
};

which will get both X(X const&) and X(X&&) etc., implicitely declared and (trivially) defined on use.

like image 579
PeterSom Avatar asked Aug 22 '12 12:08

PeterSom


People also ask

Is there a default copy constructor?

A copy constructor is automatically invoked by the compiler whenever we pass or return an object by value. We can restrict an object passed or return by value using a private copy constructor. A default copy constructor is fine, but be cautious if there is a dynamic data member.

What is the purpose of default keyword in C++ 11?

It's a new C++11 feature. It means that you want to use the compiler-generated version of that function, so you don't need to specify a body. You can also use = delete to specify that you don't want the compiler to generate that function automatically.

What is default in C++ constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Is default constructor created automatically?

The default constructor is auto-generated if there is no user-declared constructor (§12.1/5).


2 Answers

From the standard:

8.4.2 Explicitly-defaulted functions [dcl.fct.def.default]

4 - [...] A special member function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. [...]

An explicit default can be combined with its declaration, or it can be separate:

struct S {
    S();
};
S::S() = default;

In either case its (first) declaration makes it user-declared.

like image 165
ecatmur Avatar answered Nov 09 '22 07:11

ecatmur


Yes, your defaulted copy assign operator precludes the implicit move ctor.

BTW putting =default is actually a definition. I remember trying to implement a pimpl idiom with std::unique_ptr and having to remove =default from headers and putting them in the implementation file because the destructor for unique_ptr needed the definition of the class it is trying to clean up.

like image 35
emsr Avatar answered Nov 09 '22 08:11

emsr