C ++ 11: When do we need to specialize "= default" for a default member function?
A simple test and found that "= default" only works for special member functions, for example:
#include<cstdio>
#include<utility>
struct Base{
Base(int){printf("Base(int)\n");}
};
struct Derived{
Derived(int)=default;
};
int main(){
Derived d(0);
return 0;
}
clang will report a compilation error:
error: only special member functions may be defaulted
So, if only "special member function" is allowed, this "= default" seems useless: because if I don't define special member functions in "Derivatives", the compiler will generate one for me, equal using "= default ".
So my question is why and when do we need "= default"?
source to share
because if I don't define special member functions in "Derived" the compiler will generate one for me equal to using "= default".
Because there are cases where some of the special member functions will not be generated, for example. when you declare a copy constructor, the move constructor will not be generated, then the move requests will be handled by the copy constructor. Adding (the default) move constructor can prevent the following:
struct Derived {
Derived(const Derived&) { ... }
Derived(Derived&&) = default;
};
source to share
If I do not give definitions for special member functions in Derivatives, the compiler will generate one for me equal to using "= default".
No, really.
Declare any constructor - and your compiler-generated default constructor will disappear. To return it (in the form provided by the compiler), you can define it as = default
.
Provide a user-declared destructor - both your compiler-provided move constructor and the move operator are gone. To get them back, you can define them as = default
.
Provide a user-declared move assignment operator - and your compiler generated creator and copy assignment operator are gone. Well, you get the idea.
= default
used when you need to return functions provided by the compiler of a special member function in situations where other circumstances have caused the function to "disappear".
source to share