Using + operator without memory leak?

So this code is as follows:

const String String::operator+ (const String& rhs)  
{  
    String tmp;  
    tmp.Set(this->mString);  
    tmp.Append(rhs.mString);  
    return tmp;  
}  

This, of course, pushes String onto the stack and gets deleted and returns garbage. And putting it in a heap will be a memory leak. So how do I do this?

+3
source share
4 answers

Your solution does not return garbage if you have a working constructor - the String object is tmpcopied to the result object before it is destroyed at the end of the block.

You can do it better by replacing

String tmp;
tmp.Set(this->mString);

from

String tmp(*this);

(for this you need a properly working copy constructor, but you need it anyway for your operator return)

+11
source

, , . , .

+4

std::string,

( )

( String , )

+1

. String "const String".

0

Source: https://habr.com/ru/post/1728980/


All Articles