I have the following code and I think that the arr property should be allocated on the heap, because the test object is allocated on the heap.
But for some reason, the A destructor is being called, even though I do not call it explicitly. Is there explanation for this?
CODE:
class A {
public: ~A(){
cout<< "detor A"<< endl;
}
};
class C {
A arr[10];
public: ~C(){
// delete[]arr;
}
};
int main() {
C* test = new C();
delete test;
}
OUTPUT:
detor A
detor A
.
.
The destructor of an object is called when the object has to be destroyed and independently of the way the object was allocated.
For example:
a local object is destroyed automatically when it goes out of scope
an object allocated with new is destroyed with delete
a member object is destroyed in the destruction process of its enclosing object
The last cases causes the behavior that you observe: you delete test, which requires arr to be destroyed, which requires each of its items to be destroyed.
Related
Have a look at following code:
#include <iostream>
#include <memory>
class A
{
public:
A()
{
std::cout << "A() \n";
}
~A()
{
std::cout << "~A() \n";
}
int a = 100;
};
class B
{
public:
B()
{
ptr.reset(new A());
std::cout << "B() \n";
std::cout << "pointer value" << ptr.get() << std::endl;
std::cout << ptr->a << std::endl;
}
~B()
{
std::cout << "~B() \n";
}
void print()
{
std::cout << "print() " << a << b << "\n";
std::cout << "pointer value" << ptr.get() << std::endl;
std::cout << ptr->a << std::endl;
}
private:
std::unique_ptr<A> ptr;
int a = 10;
int b = 5;
};
int main()
{
std::unique_ptr<B> p1(new B());
p1->~B();
p1->print();
return 0;
}
the output result:
A()
B()
pointer value010ECB60
100
~B()
~A()
print() 105
pointer value010ECB60
-572662307
~B()
~A()
The Question is:
When class B's destructor called, class A's destructor also called, and class A's member a = 100 has been destroyed, but class B's member a = 10; b = 5 still exist, and it's value not changed, so class B's destructor can't be seen as a function, since it called class A's destructor, how to explain this?
When exit the main() function, the destructor of class B called second time automatically, and code breaks with the error code HEAP[Destructor.exe]: Invalid address specified to RtlValidateHeap( 00EA0000, 00EACE38 ), because class B's destructor called first time so object A has been destroyed, this will destroy it twice?
I add some print info to track workflow, but i still don't figure out how it worked when called the destructor explicitly.
When class B's destructor called, class A's destructor also called, and class A's member a = 100 has been destroyed, but class B's member a = 10; b = 5 still exist, and it's value not changed, so class B's destructor can't be seen as a function, since it called class A's destructor, how to explain this?
No, they do not exist, both B and A objects have been destroyed, it is just that dereferencing a dangling pointer (p1.get() during p1->print()) is undefined behaviour. In this case, the compiler just did not bother with clearing the memory locations used for the storage of the object B.
When exit the main() function, the destructor of class B called second time automatically, and code breaks with the error code HEAP[Destructor.exe]: Invalid address specified to RtlValidateHeap( 00EA0000, 00EACE38 ), because class B's destructor called first time so object A has been destroyed, this will destroy it twice?
Well, you destroyed the object held by p1 but in a way p1 was not aware it has been destroyed. Then when ~unique_ptr has been called on p1, it tried to destroy already destroyed object. Instead, you should just use p1.reset() which will call ~B and update p1's state accordingly to prevent the mentioned issue.
To really understand what is going on here, you need to understand there are really two related processes that happen when recycling an object's memory. There's destruction (which is calling the class destructor to clean up any other objects the object refers to), and there's deallocation (which makes the memory available for reuse). Normally for objects on the heap, one calls delete which does both of these things. For std::unique_ptr, its destructor call its deleter, which by default calls delete on the object the unique_ptr points at.
When you call a destructor explicitly (with p1->~B() in your case), it destroys the object but does not deallocate it. That leaves the object in a "broken" state where you can't do anything with it (not even call delete safely), but where it hasn't been deallocated either, so all you can do is kill any references to it (with .release()) and let the memory leak. So you should never call the destructor explicitly.
If you try to access an object after it has been destroyed, you get undefined behavior, but if you try it before the object has been deallocated (as you are doing in your example), you'll probably just see the same data, as the memory has not yet been overwritten by anything else.
Usually you don't need to call destructor explicitly. For automatic objects and dynamically allocated objects (using new/delete) lifetime of object coincides with liftime of its storage, and constructors and destructors called automatically. But sometimes storage is allocated separatelly and in this case constructor(well, sort of) and destructor should be called explicitly. Here is example code from: https://en.cppreference.com/w/cpp/language/new
{
// Statically allocate the storage with automatic storage duration
// which is large enough for any object of type `T`.
alignas(T) unsigned char buf[sizeof(T)];
T* tptr = new(buf) T; // Construct a `T` object, placing it directly into your
// pre-allocated storage at memory address `buf`.
tptr->~T(); // You must **manually** call the object's destructor
// if its side effects is depended by the program.
} // Leaving this block scope automatically deallocates `buf`.
Same techniques used in different containers, for example std::vector.
class A
{
public:
~A()
{
std::cout << "A destroyed" << std::endl;
}
};
class B
{
public:
A a;
~B()
{
std::cout << "B destroyed" << std::endl;
}
};
int main()
{
B b;
b.~B();
}
Output:
B destroyed
A destroyed
B destroyed
A destroyed
Can someone explain to me what's going on here? I expected the output to be
B destroyed
A destroyed
(once when ~B() is called and once ~A() is called).
Any object that was created in a limited scope would be destroyed when the scope is exited.
Meaning, that if you have created an object on the stack, it will be destroyed when the stack will fold back, along with any other variables declared in that scope.
The only exception to this is when you are using dynamic allocation of objects, using the keyword new, this creates the object on the heap, which doesn't clean itself on its own. But even then, calling delete will invoke the destructor on its own.
Having said that, in order to avoid using new and delete, and for better resource management, there are types (such as smart-pointers) that handle these on their own, in a technique called Resource Allocation Is Initialization (or RAII), which makes things much simpler (and you get to the first part, all is allocated on the stack, thus the destructors are being called automatically when it folds).
Can somebody explain here how destructor is called for object created in heap via new operator when the corresponding delete is not called.
In addition since in below code we are catching object via const reference and in destructor we are changing object value (i.e. setting n=0), so how is that possible.
class A
{
private:
int n;
public:
A()
{
n=100;
std::cout<<"In constructor..."<<std::endl;
}
~A()
{
n=0;
std::cout<<"In destructor..."<<std::endl;
}
};
int main()
{
try
{
throw *(new A());
}
catch(const A& obj)
{
std::cout<<"Caught...."<<std::endl;
}
return 0;
}
Output from program (running on http://cpp.sh/3jm4x):
In constructor...
Caught....
In destructor...
throw makes a copy of the object, which is then destroyed automatically after catch. It is this destruction that you observe. The original heap-allocated object is indeed never destroyed.
You actually have a memory leak, because the destructor that is called is not for the object allocated by new.
throw *(new A()); results in a copy of the object and you can see that the copy constructor is called. And this is the object that the destructor is called for at the end of the scope for catch.
You can check the live demo here.
EDITED: Let's say we don't call explicitely the destructor of a heap-based object (delete A). If the pointer that points to "A" goes out-of-scope, is there a way the dynamic object remain accessible? for e.g., in the following code, can "a" be still alive after if-closing }?
class A{
void itsmethod();
};
int main()
{
if (true){
A* a = new A;
}
//...here how can I use dynamically allocated object?
a->itsmethod();
}
EDIT: As it was responded, the simplest immediate way is defining the pointer outside of if statement, but I am just wondering if there is any other option to prolong lifetime of dynamic object? Accordingly what else "A" class should provide? For instance passing by reference? Or equipping the class with move constructor... These suggestions may be irrelevant, I would like to hear your feedback.
I wonder if the object "a" is still alive after if-closing }?
The object a, which is a pointer, is not alive after the closing } of the if statement. The object to which a points to is in memory but it is not accessible with the posted code.
To be able to access the object to which a points to, declare a before the if statement.
int main()
{
A* a = nullptr;
if (true)
{
a = new A;
}
if ( a != nullptr )
{
a->itsmethod();
}
}
No and Yes: yes because dynamic memory is not freed up automatically. No because the code doesn't compile because a is scoped to if block and you are trying to use it from outside.
class A{
public:
int x;
};
int main(){
A* ptrA = NULL;
if(true){
// Everything declared here is accessible only here whatever being dynamic or static.
ptrA = new A;
ptrA->x = 10;
int x;
}
if(ptrA){
std::cout << ptrA->x << std::endl; // 10
delete ptrA;
}
return 0;
}
You must free up memory always when you're done with it otherwise it is a memory leak.
Above x is declared inside the if block on the stack so when end of if block is reached x will be destructed.
The object created by the new expression (i.e. by new A) will continue to exist.
The pointer a itself, since it has passed out of scope, will cease to exist as far as your program is concerned.
The net effect is that the dynamically allocated object is "leaked". It continues to exist after the block but there is no pointer or reference to it.
If you do something like
int main()
{
A *b;
if (true)
{
A* a = new A;
b = a;
}
a->itsmethod(); // diagnosible error
b->itsmethod(); // will work correctly
delete b; // destroy dynamically allocated object
b->itsmethod(); // undefined behaviour
}
then a->itsmethod() will give a compiler diagnostic (since a no longer exists) but the first b->itsmethod() will use the object created by the new expression. The second b->itsmethod() will compile, but yield undefined behaviour, since it accesses an object that no longer exists (due to the preceding delete b).
This happens because the pointer b continues to exist and, within the enclosed block, is assigned the value from a. So it then contains the result of the new expression.
No. The object 'a' will not be accessible anymore since its scope belongs to the if statement. However, there still is a memory address containing that object. This is why its good to do 'garbage collection' in programming.
Let's consider this demonstrative program
#include <iostream>
struct A
{
const char *s;
std::ostream & operator ()( std::ostream &os = std::cout ) const
{
return os << s;
}
};
int main()
{
A *a1;
if ( true )
{
A *a2 = new A { "Hello, Sepideha" };
a1 = a2;
}
( *a1 )() << std::endl;
delete a1;
return 0;
}
Its output is
Hello, Sepideha
Here the object a1 that has the type A * has the outer-most block scope of the function main.
The object a2 has the block scope of the if statement. It is alive only within this block.
At the same time there is dynamically created unnamed object of the type A pointer to which is assigned to a2 and then to a1. This unnamed object will be alive until the operator delete for a pointer that points to the object will be called. That is its live-time does not depend on the block scope of the if statement.
Because the pointer a1 points to this unnamed object then the pointer can be used outside the if statement to access the unnamed object in the dynamic memory.
After the statement with the delete operator this unnamed object stops to exist. But the object a1 is still alive.
Suppose a class and its usage
#include <vector>
class B
{
public:
B() {temp = 0;}; // implemented
~B() {} ; // implmented
private :
int temp;
// it holds a std::bitset , a std::vector.. It is quite large in size.
};
class A
{
private:
std::vector<B*> * _data ;
public:
A()
{
_data = new std::vector<B*>(0);
}
~A()
{
for(unsigned int idx_ = 0; idx_ < _data->size(); ++idx_)
delete _data->at(idx_);
delete _data ;
}
void addB()
{
B * temp = new B();
_data->push_back(temp);
}
}
int main()
{
A temp;
temp.addB();
// Do something
}
My question is does this code leak memory ? Also suppose another usage
int main()
{
A * temp = new A();
temp->addB();
delete temp ; // 1
}
Is 1 here required ? If I have a pointer to the heap and the pointer goes out of scope is the destructor called on the element in heap. I just want to be sure about this point.
Thank you !
To make it easier to associate when a destructor will be called and when it wont be, use this rule of thumb: When the memory for an object is being reclaimed, then the object's destructor is called (and the memory is reclaimed right after that).
Your first example does not leak any memory.
Here is why... You essentially created 2 objects.
A and B.
A was on the stack. The memory for object A was created implicitly on the stack.
B was created on the heap explicitly by your code.
When main() returned every Object on the stack is destroyed. i.e the memory that was being used to hold the members of the object on the stack (in this case object A) is being reclaimed implicitly. Since the object (A) is actually being destroyed and its memory being reclaimed, the destructor for A gets called.
Within A's destructor you are explicitly telling the runtime to reclaim all the memory what was explicitly allocated by your code (i.e when you call delete). Thus the memory for object B is being reclaimed too.
Thus there was no leak.
In the 2nd example, you again create 2 objects A and B.
Here, the memory for both objects resides in the heap. This was allocated explicitly by your code using the new operator.
In this case, your code never reclaims the memory allocated for A. i.e delete is never called for A.
The stack for main() only contains the memory for a pointer to A. The main() stack itself does not contain the memory for A. So when main() returns, all that is being destroyed is the memory that was allocated for the pointer to A, and not A itself.
Since the memory for A was never reclaimed, it was never "destroyed". Thus its destructor was never called and correspondingly "B" was never destroyed either.
No, destructor is not implicitly called. you have to delete temp, at which time it's destructor is called. It could be argued that since it's main that's returning in your example, the process is going to exit and memory will be reclaimed by OS, but in general, each new needs a delete.
The rule of thumb is if you've used new to create something then you have to use delete to destroy it. Pointers are all about manual memory management (they are heritage from the C language) or, as Scott Meyers once called them, "running with scissors". References are a C++ thing (or you can also check out smart pointers like std::shared_ptr).
UPDATE
I thought it would be useful to show an example with std::shared_ptr. It has dumb pointer semantics, but its destructor -since it actually has one- calls pointed object's destructor.
#include <memory>
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
struct Simple {
std::string txt;
Simple(const std::string& str) : txt(str) {}
Simple(){}
~Simple() { cout << "Destroyed " << txt << endl; }
};
template<class U> using SPtr = shared_ptr<U>;
template<class V> using PtrToSimple = typename conditional<is_same<SPtr<Simple>, V>::value,SPtr<Simple>,Simple*>::type;
template<class T>
void modify(PtrToSimple<T> pt) {
pt->txt.append("_modified");
// equivalent to (*pt).txt.append("_modified");
}
int main() {
auto shared = shared_ptr<Simple>(new Simple("shared_ptr_obj"));
modify<decltype(shared)>(shared);
cout << shared->txt << endl;
auto dumb = new Simple("dumb_ptr_obj");
modify<decltype(dumb)>(dumb);
cout << dumb->txt << endl;
// The object pointed by 'shared'
// will be automatically deleted.
// dumb's object won't
return 0;
}
prints
shared_ptr_obj_modified
dumb_ptr_obj_modified
Destroyed shared_ptr_obj_modified