Delete pointer of a class with pointer variables

What will happen when I execute following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A {
    int value;
public:
    A(int value) : value(value) {}

};

class B {
    A *a;
public:
    B(A *a) : a(a) {}
};

int main() {
    A a(1);

    B *b = new B(&a);

    delete b;
    return 0;
}


delete b; line will delete content of object B. I understand that instance of A won't be deleted, but what will happen with the pointer variable 'a'? Will be the variable memory cleaned( I don't care about actual object)?

Last edited on
> but what will happen with the pointer variable 'a'? Will be the variable memory cleaned

As far as the programmer is concerned, the object pointed to by b does not exist after delete b ;
Accessing any non-static member of the object (for instance the member a)
after that engenders undefined behaviour.

It is another matter that a smart compiler (clang++) may rewrite the code for main as: int main() { return 0 ; }
https://godbolt.org/g/3dnDaU

As-if rule: See http://en.cppreference.com/w/cpp/language/as_if
Elision of allocations with new expressions: http://en.cppreference.com/w/cpp/language/new#Allocation
Memory for b->a will deallocated when b is deleted, just the same as if B::a was an int instead of an A *. However, the variable that b->a points to will be unaffected.

Use of raw pointers in classes can be dangerous. If you're going to use them, be sure to clearly define and document who owns the pointer. Better yet, use smart pointers instead.
> Memory for b->a will deallocated when b is deleted

There is no separate memory allocation or deallocation for non-static member objects.
A non-static data member (of some non-reference type) is a sub-object of the complete (class) object.

6.6.4.5 Duration of subobjects
The storage duration of subobjects and reference members is that of their complete object
http://eel.is/c++draft/basic.stc.inherit
There is no separate memory allocation or deallocation for non-static member objects.

I didn't mean to imply that there was. Still, thanks for the clarification.
Registered users can post here. Sign in or register to post.