Got such a problem - I do not know how to fix it. There is the following code:

Foo& operator+(const Foo& other) { Foo result(this._field + other._field); return result; } 

In the class there is a pointer field, respectively, in the constructor it is initialized through new, in the destructor it is deleted through delete. And here's the problem: upon the completion of the operator’s work, the destructor is called for result! well, it is clear that in a place like Foo foo = A + B; (where A and B are also clear to Foo) the destructor will be called again. I get 2 release.

  • Can anyone explain why (or why?) Minus such questions? (the question is, of course, rhetorical, almost no one will see it with the current engine) - avp

2 answers 2

My crystal ball says you forgot to define a copy constructor.

In this case, the default copy constructor is called up, which simply copies all fields, including the dying pointer. For everything to be correct, you must allocate new data in the copy constructor, and not assign the same pointer, otherwise if one of the objects dies, the data in the other will be corrupted.

Destructor for result will be called, because you place it on the stack, in the frame that dies. On the other hand, a smart compiler with optimization enabled will most likely make copy elision, and throw out unnecessary copying.


If you use a modern C ++ compiler, it would be more efficient to define a displacement constructor as well. (But this does not eliminate the need for a copy constructor.)


Do not forget that in addition to the copy constructor, you need to define an assignment operator. Refresh in memory the “ rule of the big three ” (or five, applied to C ++ 11).

  • Yes thank you. To be honest, it was someone else's awful code, the author of which convinced me that there was a copy designer, only deep somewhere =) - Alexey Sarovsky
  • The power of the crystal ball !!!!! - rikimaru2013

Your function returns a reference to a local variable. The local variable is destroyed when the function exits, and the link remains to indicate nowhere. This cannot and will not work in principle, what constructors you define.

You are obviously trying to implement a binary operator + . Such an operator must return the result by value, not by reference.

  • Yes, I have already rewritten and created an object in the heap - Alexey Sarovsky
  • @AlekseySarovsky: It’s not necessary to create an object on the heap (this will most likely lead to a memory leak), just return by value. Foo operator+(const Foo& other) (without the first & ). - VladD
  • @ Alexey Sarovsky: In a heap? Not seeing the whole code is difficult to judge the meaningfulness of such a decision, but most likely it will end in a memory leak. No need to create an object on the heap. Just write the correct constructors and return the object by value . - AnT