OK,I am reading "effective C++" and item 12 says please don't call copy assignment in copy constructor.But after I try to do this, it does work. So I want to ask why, I can't reuse the copy assignment code in copy constructor?
Asked
Active
Viewed 115 times
-1
-
1I think it's because probably more effective member initialization through taking direct copies of them in the initializer list. – πάντα ῥεῖ Oct 27 '13 at 09:03
-
6I have a feeling this is well explained in item 12 of "Effective C++". – juanchopanza Oct 27 '13 at 09:04
-
1Hopefully all answer will be explaining more or less the same thing what Scott has explained there in _Item 12_ – P0W Oct 27 '13 at 09:09
-
1Near the end of the item 12, you have an explanation: "Performing an assignment on an object under construction would mean doing something to a not-yet-initialized object that makes sense only for an intialized object" – lolando Oct 27 '13 at 09:11
2 Answers
0
Assume you use copy-assignment operator in copy-constructor. Then you lose the ability to implement copy-and-swap idiom for assignment operator:
struct A
{
A (const A &a)
{
*this = a; // Assignment to a not yet constructed object is not well
}
A &operator=(A a) // Pass by value
{
// ...
}
};
A a1, a2;
a1 = a2; // Infinite recursion!
It's not possible and infinite recursion will occur.
-
1Thanks, I think it is useful. It will cause infinite recursion if the argument is passed by value and it's not well to assign to a not ye constructed object. Sorry I don't have enough reputation to vote up. – lingjieyu Oct 27 '13 at 10:45
0
A constructor creates a new object; an assignment operator modifies an existing object. You can't use an assignment operator to create a new object: it doesn't know how to do that, even if it seems to work in simple cases.

Pete Becker
- 74,985
- 8
- 76
- 165