user3885616
user3885616

Reputation:

Managing memory for a single string

To take in a string (including spaces) and write it to a file, I use:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream myFile("readme.txt");

    string a;
    getline(cin, a);
    myFile << a;

    myFile.close();
}

But should I be managing the memory assigned to the string, and if so what's the easiest way?

Upvotes: 0

Views: 95

Answers (4)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

No, you don't need to. Unlike C (where strings are pointers to arrays that have to be managed), The std::string class is an object which manages its own memory. The memory for a is released correctly when the variable a goes out of scope at the end of the program.

Upvotes: 1

4pie0
4pie0

Reputation: 29724

In C++ string template class provided in is a typedef for std::basic_string<char> and it manages the memory dynamically. So you shouldn't. You have still options however to help this class in this task. String provides for this purpose appropriate interface, for example

void reserve( size_type new_cap = 0 );

Informs a std::basic_string object of a planned change in size, so that it can manage the storage allocation appropriately.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 595402

As others have stated, std::string (a d every other STL container, for that matter) manages its own memory, and will be freed when it goes out of scope. If you want more control over when it goes out of scope, you can do this:

int main()
{
    ofstream myFile("readme.txt");

    {
    string a;
    getline(cin, a);
    myFile << a;
    } // <-- string is freed here

    // do other things...
}

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

No, std::string manages its own memory.

Upvotes: 4

Related Questions