May memory leak in vector<>?

I am confused about the memory mechanism in cpp, here is a example.

1
2
3
4
5
{
  vector<A> a = {A("object1"), A("object2")};
  a[0].print();
  a[0] = A("object3");
}


I found the code will not call the destructor of A("object1") who's memory had been overed by another A object. and If A has dynamic memory, memory leak happens.

what's more,
1
2
3
4
{
  vector<vector<int>> a = {vector<int>({1,2,3}), vector<int>({4,5,6})};
    a[0] = vector<int>({7,8,9});
}

for this code , suppose vector has dynamic memory, then the memory of vector<int>{1,2,3} will leak, cause vector<vector<int>> will not call destructor of vector<int> just like last example.



My question is :
Why the memory leak happens so easy? Do i fall into some error?



here is the code of A
and output of the first example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using namespace std;
class A{
     
private:
    string objName;
public:
    A(string name):objName(name) {
        cout << objName << "::A() " << endl;
    }
    ~A() {
        cout << objName << "::~A() " << endl;
    }
    void print(){cout << "name is " << objName << endl;}
};


output of first example:
object1::A()
object2::A()
object2::~A()
object1::~A()
name is object1
object3::A()
object3::~A()
object3::~A()
Last edited on
Why the memory leak happens so easy?
Assumption is wrong, there is no memory leak.

Assignment of the value of object b to object a, such as
a = b
Doesn't require that the destructor of a is called.
Last edited on
You should consider logging the copy/move constructor/operators. You're only seeing part of what's happening.
Topic archived. No new replies allowed.