issuse about “new vector”

1
2
3
4
5
6
7
8
9
10
11
class Example
{
public:
void Push(string& roStr){m_oVecStr.push_back(roStr);}
vector<string> m_oVecStr;
};

Example* pExample = new Example();
string A("test");
pExample->Push(A);
delete pExample;

//my question is ,
1. how does this delete perform?
2. will the 'vector' be destroyed after destruct?
3. in such case, the content of 'vector' is alloced in stack or the heap?
4. how does the strings in the vector be recycled?
I'm not sure what you mean by "perform". delete will free up all the memory that was dynamically allocated at line 8.

At line 8, the entire object, including all its data members, is allocated dynamically on the heap.

So that means that m_oVecStr is also allocated on the heap, as a component of the Example object.

When you delete the memory for an object, then all the memory is freed, including the memory that was allocated for the object's members. This means that when you delete the Example object, the vector is also deleted.

When you push an element onto a vector, it is copied into the vector. The vector allocates memory for its own copy of the data, and manages that memory. When the vector is deleted, then the memory used to store those copies is freed up.

So when you delete the object, the vector and all the strings in the vector are deleted, and the memory is freed. However, A is not affected - it is still available.

I think that answers all your questions.
thx @MikeyBoy
Topic archived. No new replies allowed.