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

前端 未结 2 1061
借酒劲吻你
借酒劲吻你 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 10:54

    When the b object gets pushed onto the vector a copy is made, but not by the operator=() you have - the compiler generated copy constructor is used.

    When the main() goes out of scope, the b object is destroyed and the copy in the vector is destroyed.

    Add an explicit copy constructor to see this:

    MyClass( MyClass const& other) {
        cout << "copy ctor\n";
    };
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题