s copy constructor
The idea of copy constructor really confuses me. I don't understand 开发者_开发技巧why they use references and why constant references in copy constructor?
Why you use a reference: if you didn't, you'd have to create a copy of the object you want to copy. That would have to be done with a copy constructor. Insert infinite loop here.
Why a const reference: you want to guarantee that the object you're copying is not being modified.
[Edit] As DeadMG states in his comment, you also want the reference to be const
so that you can create a copy of a temporary instance. E.g. suppose you have:
class Matrix
{
Matrix const operator+ (Matrix const & rhs) const;
// Code & stuff
}
You want the return value to be const
, so that stupid things such as the following raise a compiler error:
Matrix a, b, c;
(a + b) = c;
Now obviously that's a silly statement, but if the return type from operator+
wasn't const
, it would actually be allowed. Of course, on the next line, the temporary (a + b)
would go out of scope and you would be unable to ever use it.
However, as said before, you want to be able to create an instance with a temporary instance:
Matrix a, b;
Matrix c(a + b);
If the argument to the copy constructor wasn't const
, that wouldn't be possible, since the return type from operator+
is const
.
A C++ "reference" type can simply be thought of as a constant pointer that is initialized to the value of the address of an object ... in other words a reference can never be NULL, it has to point to some object. It therefore can also be implicitly dereferenced behind-the-scenes for you by the complier, so you do not have to worry about managing the pointer itself, as well as associated pointer syntax.
So with a copy constructor, you are basically passing a constant pointer to the object you're copying into the copy constructor function ... you're not copying the object itself. If you did have to copy the object itself into a temporary object that is then used by the copy constructor to create a new copy, as noted previously, you'd end up with an infinite loop since what would have copied the object into the temporary object in the first place? On the other hand, if you are just moving a pointer around, then there is no copy-constructor needed to get the object you want to copy into the copy constructor function. Reference syntax is used rather than an actual constant pointer though because 1) a reference can't be NULL (if it was pointer-syntax, we could pass a NULL to a constant pointer), and the by-product of that means 2) a lot of things are simpler, including the syntax since the compiler can do the implicit dereferencing of the passed-in reference pointer for you, so you can use normal member-accessing syntax like myclass.member_function()
rather than myclass->member_function()
.
Hope this helps,
Jason
精彩评论