-1

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?

lingjieyu
  • 21
  • 2
  • 1
    I 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
  • 6
    I have a feeling this is well explained in item 12 of "Effective C++". – juanchopanza Oct 27 '13 at 09:04
  • 1
    Hopefully 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
  • 1
    Near 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 Answers2

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.

Community
  • 1
  • 1
masoud
  • 51,434
  • 14
  • 119
  • 190
  • 1
    Thanks, 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
  • 69,019
  • 6
  • 64
  • 147