问题
I am reviewing the cppreference page on copy constructors here: http://en.cppreference.com/w/cpp/language/copy_constructor
I've read the 2 sections regarding implicitly-declared copy constructors and implicitly-defined copy constructors quite a few times but I still don't understand the distinction. Wouldn't an implicitly declared but NOT defined constructor result in linker problems?
The rules are very complex. I don't remember there being a distinction in C++03: Either you had a compiler generated copy constructor or you didn't.
Can someone explain (in simpler words) what the distinction/differences are between these two categories?
回答1:
This is clarified in a note in the standard at the beginning of clause 12:
[ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are odr-used (3.2). See 12.1, 12.4 and 12.8. — end note ]
Normative references for C++14 (N3936) are 12.1/5, 12.4/6, 12.8/13, 12.8/26. In each case the corresponding special member function is implicitly defined if it is defaulted and not defined as deleted, and either odr-used or explicitly defaulted. If we have something like
struct Foo {};
and no objects of type Foo
are ever created, all six special member functions (default constructor, destructor, copy constructor, move constructor, copy assignment operator, move assignment operator) are implicitly declared as defaulted, but not defined since they are not odr-used.
回答2:
If there is an implicitly-declared copy constructor, it is always defined1. The options for its definition are:
- deleted
- trivial
- implicitly-defined
If a program tries to use a constructor which is defined as deleted then the program is ill-formed (i.e. you get a compiler error). In the other cases, the function is called.
The page you link describes in which situations each of the three above options occur.
C++11 added the concept of a delete
d function, for when you want to explicitly make a class be non-copyable (etc). You define its copy-constructor as deleted and then the compiler generates an error if someone tries to copy your object.
The distinction between trivially copyable and not trivially copyable was always there but it was not stated quite so clearly; you inferred from the rules about PODs in which situations it was permitted to use memcpy
to copy objects.
1As Brian points out, it is more accurate to say that it is defined if required. The compiler never implicitly declares a function and then generates a link error. But if the function definition is not required to successfully build the executable, it won't bother actually forming the definition.
来源:https://stackoverflow.com/questions/26149463/what-is-the-distinction-between-implicitly-declared-and-implicitly-defined-copy