string *str=new string;
vector<string *> vector;
vector.push_back(str)
in brief, I want know when vector of pointers out of scope, is the pointer's self's occupied space freed?
string *str=new string;
vector<string *> vector;
vector.push_back(str)
in brief, I want know when vector of pointers out of scope, is the pointer's self's occupied space freed?
Your question is a little unclear, but I guess, you want the strings to be allocated dynamically, yet automatically freed after the vector goes out of scope, right?
Vector will destroy only its contents when it is destroyed. That means, when the vector goes out of scope, it will destroy pointers held on its list, but it won't destroy objects pointed to by these pointers. So it may result in memory leak.
Actually, there are a few solutions to this problem. You can store instances of std::string instead of pointers to std::strings:
std::vector<std::string> strings;
strings.push_back("Alice has a cat");
When strings
goes out of scope, all strings will be destroyed.
Another option is to use boost (in case you use C++ pre-11) or std (in case you use C++11) class called shared_ptr or unique_ptr. It behaves more less like a pointer, but when it goes out of scope, it destroys the contained object. So if you declare your list like this:
std::vector<std::shared_ptr<std::string>> strings;
std::push_back(std::make_shared<std::string>("Alice has a cat"));
String will be allocated dynamically, and be freed automatically (vector will free all shared_ptr's and if there are no more references to held strings than in these pointers, they will free strings as well).
Read further: