Reputation:
If I create an object without using the new keyword such as 'Object s(someval)', but that objects constructor uses new, when that object goes out of scope, will the destructor be called for it's new allocation? I feel as though it is, but I'm unsure.
Upvotes: 0
Views: 751
Reputation: 545885
Let’s give names to the objects, shall we?
struct A {
A() b(new B) {}
B* b;
C c;
};
A a;
Here, a
’s destructor is called. So is A::c
’s destructor (which is called automatically when a
is destructed).
However, *A::b
’s destructor is not called – actually, the pointer object A::b
itself is properly released but since it’s a primitive type (it’s a pointer!) nothing happens. The pointee *A::b
however needs to be manually destructed (and its memory released) by calling delete
.
Upvotes: 3
Reputation: 126502
when that object goes out of scope, will the destructor be called for it's new allocation?
It depends on how Object
is defined.
If the pointer returned by new
is stored in some data member of Object
on which delete
gets called by the destructor of Object
itself, then yes, the object allocated with new
will be destroyed as well when s
goes out of scope.
Otherwise, no. Every call to new
must be matched by a corresponding call to delete
before you lose the last pointer/reference to the allocated object, otherwise you will have a memory leak.
Since it is easy to fail to do so, and since it is also easy to dereference by mistake a pointer which is dangling (i.e. pointing to an object whose lifetime has ended), it is usually preferable to avoid performing manual memory management through raw pointers, new
and delete
(or their array counterparts).
When you need to control an object's lifetime, always prefer using RAII wrappers such as std::shared_ptr<>
or std::unique_ptr<>
unless you really know what you are doing and can't do otherwise.
Upvotes: 2
Reputation: 496
No you will have to call delete explicitly for that object in the destructor
Upvotes: 0
Reputation: 13207
No, it won't...
You have to define the delete
in your destructor of the object you allocated using new
.
You create an object on the heap using new
and when your object is destroyed you will lose the reference to the object creating a memory-leak.
To avoid this, you might use a smart-pointer like shared_ptr
.
Upvotes: 0
Reputation: 61970
No, you have to explicitly delete
it in the destructor if you store that dynamically-allocated pointer as a data member. This also introduces the Rule of Three (Rule of Five in C++11), which is a bother. This is why stack-allocated objects should be preferred when possible.
When a pointer is necessary, make use of an RAII wrapper, such as std::vector
for a dynamically-allocated array or a smart pointer, such as std::unique_ptr
or std::shared_ptr
, for a single dynamically-allocated object. These manage the memory for you and to you, it's no extra work.
Upvotes: 0