Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 954
  • Last Modified:

string Deallocation

Guys,
I know string destructor class destroyes a string. Wanted to make sure, if (like in C free()) there is anything we need to explicitly call to deallocate the string in C++?

say:
#include <iostream>
#include <string>

void main()
{
std::string str("sad");
cout<<sad<<endl;

// Do we need to free the string here? or deallocate the assigned memory??

}

Please let me know.
0
pbavishi
Asked:
pbavishi
  • 2
1 Solution
 
ExceterCommented:
>> // Do we need to free the string here? or deallocate the assigned memory??

No. You do not need to free or delete memory allocated by std::string. The class destructor takes care of that for you.

Exceter
0
 
ExceterCommented:
>> std::string str("sad");
>> cout<<sad<<endl;

By the way, this will not compile. Your string is named str. sad is the text in your string.

Exceter
0
 
Fallen_KnightCommented:
no, if you don't use the new operator you don't need to free or delete anything at all.

if you had gone

string *str = new String("sad");
cout << str;

//you would have to go:
delete str;


even thou exiting the program free the memory anyway its best to always get into the habit of deleteing what you allocate with new
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now