问题
Why is the argument of the copy constructor a reference rather than a pointer?
Why can't we use the pointer instead?
回答1:
There are many reasons:
References cannot be NULL. OK, it's possible to create a NULL reference, but it's also possible to cast a
std::vector<int>*
into astd::vector<SomeType>*
. That doesn't mean such a cast has defined behavior. And neither does creating a NULL reference. Pointers have defined behavior when set to NULL; references do not. References are therefore always expected to refer to actual objects.Variables and temporaries cannot be implicitly converted into pointers to their types. For obvious reasons. We don't want pointers to temporaries running around, which is why the standard expressly forbids doing it (at least when the compiler can tell you are doing it). But we are allowed to have references to them; these are implicitly created.
Because of point number 2, using pointers rather than references would require every copy operation to use the address-of operator (&). Oh wait, the C++ committee foolishly allowed that to be overloaded. So any copy operation would need to actually use std::addressof, a C++11 feature, to get the address. So every copy would need to look like
Type t{std::addressof(v)};
Or you could just use references.
回答2:
It's just nomenclature. You can use a pointer as well, but that'd be called a conversion constructor.
If you think about it, it makes sense, because you copy one object to another (ergo the "copy"). Not from a pointer to an object. If it was a pointer, it wouldn't do a copy, because you're not copying the pointer to the object, but rather the object the pointer points to to your object.
回答3:
Why should it be a pointer? A null pointer wouldn't make sense. And using a pointer wouldn't allow copying temporaries, so you couldn't do things like:
MyClass
func()
{
// ...
return MyClass(...);
}
You can define a constructor taking a pointer. But it won't be a copy constructor, because it couldn't be used in cases like the above. And it won't inhibit the compiler from generating a copy constructor.
回答4:
Because this is denied by the standard.
Quoting from C++ draft standard n3376 - section 12.8.2:
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments
回答5:
Because a pointer could be a nullptr
which would have to be checked and temporaries can't have pointers to them.
回答6:
Passing by references ensures an actual object is passed to the copy constructor, whilst a pointer can have NULL value, and make the constructor fail
来源:https://stackoverflow.com/questions/18611475/why-is-the-argument-of-the-copy-constructor-a-reference-rather-than-a-pointer