string Deallocation

Posted on 2003-02-21
Medium Priority
Last Modified: 2012-08-13
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++?

#include <iostream>
#include <string>

void main()
std::string str("sad");

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


Please let me know.
Question by:pbavishi
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2

Accepted Solution

Exceter earned 200 total points
ID: 7995118
>> // 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.


Expert Comment

ID: 7995992
>> 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.


Expert Comment

ID: 7996970
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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question