Puneet Mittal
Puneet Mittal

Reputation: 542

deleting a string object in c++

I have a const char* str and i wanted to convert it to a simple string so i used the std::string() constructor and copied the value of str into my variable.

    const char* str;
    std::string newStr = std::string(str);

    <some processing>...
    <end>

So before the end of the function do i have to delete the string newStr or the destructor of std::string class is called automatically and this newStr will be deleted. I am confused as i read here that the destructor of std::string class is not virtual. But here it says that the string will be deleted as it goes out of scope. Can anyone throw some light on it as it seems confusing if the destructor is not virtual, how come the string variable gets deleted after it goes out of scope.

Upvotes: 0

Views: 360

Answers (2)

Baz
Baz

Reputation: 84

Since you did not create the object with the new keyword, the object is created on the stack and the destruct-or is called automatically when the variable goes out of scope. However, when you create your object with the new keyword your object is created on the heap. This is the general rule in C++.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

You do not have to delete newStr. It has automatic storage, so it's destructor will be called when it goes out of scope. That has absolutely nothing to do with the destructor being virtual.

Upvotes: 4

Related Questions