0

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.

Community
  • 1
  • 1
Puneet Mittal
  • 532
  • 1
  • 15
  • 24
  • 4
    Did you `new` it? If not, so no need for `delete`. – chris Oct 29 '12 at 19:45
  • 1
    You seem to have some misconceptions about what `delete` is for, and about the reasons that destructors should (often) be `virtual` . . . – ruakh Oct 29 '12 at 19:47
  • 4
    Simple rule: Exactly one `delete` for each `new`, exactly one `delete[]` for each `new[]`. You don't have a `new` so you don't need a `delete`. – Robᵩ Oct 29 '12 at 19:47
  • 1
    Also, less typing, same result; `std::string newStr(str);` – Ed S. Oct 29 '12 at 19:50
  • 1
    There is a problem with the code given which has nothing to do with the OP's question. Since `str` is uninitialized, the value of `newStr` will be undefined. – Code-Apprentice Oct 29 '12 at 19:50
  • @Code-Guru yes i know about the problem, its just for asking the question i typed it without initializing, but in my function it is passed as an argument so its not undefined. Thanks for pointing out the error, i will remember it next time. – Puneet Mittal Oct 29 '12 at 20:08
  • @PuneetMittal For future reference, it is helpful to post code that reproduces what you are asking about and doesn't introduce any other errors. For one thing, this will make your question (and the answers) more useful to anyone that encounters the same problem in the future. – Code-Apprentice Oct 29 '12 at 20:20

2 Answers2

4

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thanks i get it. Since i didn't create the object using new, its an auto variable which gets destroyed after it goes out of scope. Thanks. – Puneet Mittal Oct 29 '12 at 20:09
0

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++.

Baz
  • 92
  • 3