C++ basic constructors/vectors problem (1 constructor, 2 destructors)

前端 未结 2 1064
借酒劲吻你
借酒劲吻你 2020-12-11 10:24

Question is probably pretty basic, but can\'t find out what\'s wrong (and it leads to huge of memleaks in my app):

class MyClass {
public:
    MyClass() { co         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 11:12

    If you want to log all copies and constructions you should add an explicit copy constructor so that the compiler doesn't create one for you.

    MyClass( const MyClass& )
    {
        cout << "Copy constructor\n";
    }
    

    You can, in your copy constructor, call your assignment operator. It is a reasonably common way of implementing things, however with your definition of operator=, this may have serious problems.

    You have an unconventional implementation of operator=. operator= should return a reference to the class on which it is called (to enable proper chaining), but you return a new class instance by value. This means that if you tried to call operator= from your copy constructor you may well end up with infinite recursion. Try this operator= instead:

    MyClass& operator=( const MyClass& )
    {
        cout << "operator=\n";
        return *this;
    }
    

    When defining an assignment operator you should always consider the possibility that the parameter and *this may refer to the same object and ensure that the definition of the operator won't have any unintended effects in this scenario.

提交回复
热议问题