De-referencing of heap object - is there a leak?

Is this code safe in terms of memory leaks? And if yes, why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class A {
    int value;
public:
    A(int value) : value(value) {}

    virtual ~A() {
        std::cout << "A is destroyed\n";
    }

    int getValue() const {
        return value;
    }
};

A *getA() {
    return new A(7);
}

void doSomething() {
    A a = *getA();
    std::cout << a.getValue();
}

int main() {
    doSomething();
    return 0;
}


Basically getA method allocates memory in heap. I de-reference it in doSomething method. It looks like the destructor is called after doSomething is done. Does it mean that original heap memory was cleaned? if yes, why? Was it copied into stack of the function? Or I actually leaked the memory? And if there is a leak, what object was destructed


Last edited on
Is this code safe in terms of memory leaks?

No.

And if there is a leak, what object was destroyed?

The unnamed object created by getA() has dynamic storage duration. That object is copied into the local object named a inside doSomething(), which has automatic storage duration. That local object (with automatic storage duration) is destroyed when the function returns.

Objects with dynamic storage duration are never destroyed automatically - the programmer is responsible for ensuring they are explicitly deleted.
Last edited on
to be fair, simply making getA return the correct pointer type fixes it:

1
2
3
auto getA() {
    return std::make_unique<A>(7);
}


full demo: https://wandbox.org/permlink/XOom13EGK3pH2vbf
Registered users can post here. Sign in or register to post.