JuliusCaesar
JuliusCaesar

Reputation: 351

C++ when does a string Destructor gets called

let's say i have this setup:

struct My_Struct_T
{
//some stuff
string my_string;
//some other stuff
}

My_Struct_T myVar = {};

string Set_String()
{
string res = "Second String";
return res;
}


void Foo()
{
    myVar.my_string = "First String";

    //do some stuff 

    //do i have a memory leak after this line?
    myVar.my_string = Set_String();
}

at first myVar contains a pointer to string "First string" (the actual content of the string is located on the heap of course).

Now when i'm calling the set_string() function i'm asuming i'm simply overwriting the pointer. However since i'm not destroying the acutal string object no destructor is called and therefore i got a memory leak. Is that correct? :)

Upvotes: 0

Views: 888

Answers (2)

Aconcagua
Aconcagua

Reputation: 25536

No, it is not. std::string is designed to handle its memory internally – and correctly, i. e. it will release (delete) the internal string buffer any time it needs to allocate a new one.

Efficient implementations even try to reuse the internal buffer as long as possible (i. e. assigning new content just overwrites the old one in one and the same location, if it fits in).

Be aware that assigning a string literal or any other char (const) pointer will result in the std::string object copying the assigned data into some internal buffer, which especially means it won't take ownership of the pointer. You get a memory leak if you new an array, assign it to a std::string and don't delete it afterwards...

Upvotes: 2

Temple
Temple

Reputation: 1631

No, assignment operator will be called on temporary which will be destroyed.

Upvotes: 1

Related Questions