Destructor direct call in C++ - c++

Hence the code below.
class A
{
int x;
public:
A() {x = 3;}
};
int main()
{
void* mem = operator new(sizeof(A));
A* obj = static_cast<A*>(new(mem)(A));
std::cout << obj->x << std::endl;
obj->A::~A();
std::cout << obj->x << std::endl;
}
My first question is: Why I can directly call the destructor of A;
My second question is: Why the output is:
3
3
The the object obj is not deleted after the destructor call? The second 3 bothers me.

Why can I call the destructor?
Because it is a public member function, and you can call public member functions.
Why is the object not deleted?
In your specific case, it still exists because A has a trivial destructor.
If it had a non-trivial one, it would be deleted in the sense that you are not allowed to use it anymore. If you do anyways, you have undefined behavior.
For a more detailed discussion on that read this.

Related

Why the output is different from what I expect?

I got a simple program like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
class B {
protected:
int data = 0;
public:
B() { cout << "B() ctor\n";}
virtual ~B() { cout << "~B()\n"; }
virtual void method() { cout << "data in B: " << data << "\n"; }
};
class A : public B
{
int dataA = 2;
public:
A() { cout << "A() ctor\n"; }
~A() { cout << "~A()\n"; }
void method() { cout << "data in A: " << dataA << "\n"; }
};
{
B* fptrList[]{ &B{}, &A{}};
for (auto& itr : fptrList)
itr->method();
}
cin.get();
return 0;
}
Here is a result I expect:
B() ctor
B() ctor
A() ctor
data in B: 0
data in A: 2
~A()
~B()
~B()
Here is the actual result when I ran this program:
B() ctor
~B()
B() ctor
A() ctor
~A()
~B()
data in B: 0
data in B: 0
My questions are:
Why the output is different from what I expect?
How can method() be called after ~A() and ~B() get called?
Why method() of class B get called twice?
This program cannot be explained, because it exhibits undefined behavior.
Translation: it's buggy. It's taking an address of temporary objects, and then attempts to dereference them, after the temporary have been destructed.
A good C++ compiler will even tell you that the program is broken, and will refuse to participate in this disaster:
t.C: In function ‘int main()’:
t.C:26:27: error: taking address of temporary [-fpermissive]
B* fptrList[]{ &B{}, &A{}};
^
t.C:26:33: error: taking address of temporary [-fpermissive]
B* fptrList[]{ &B{}, &A{}};
^
Any output from this program is meaningless garbage.
Here is what's going on:
You initialize fptrList to addresses of temporary variables A and B
The temporary variables get destroyed right after their addresses are taken, so your code has undefined behavior.
Proper way of doing what you are trying to do it is to use operator new with smart pointers, or to make instances outside initializer.
Here is one possible fix:
{
B b;
A a;
B* fptrList[]{ &b, &a };
for (auto& itr : fptrList)
itr->method();
}
Ok, it is undefined behavior, but the question is still interesting why it is this undefined behavior.
Why are constructors/destructors are called in this order? As already established, you creates temporary objects which are created/destroyed one after each other.
Why can I call methods of already non-existent objects? Your temporary object lives at the stack and thus the memory will be freed only at the end of the main function, so you are still able to access this memory and it does not get clobbered by calls to other functions (e.g. printing to the terminal). If you would create the object with new, than delete it and than try to use it - the chances would be higher, that the system has already reclaimed this memory and you would get a segmentation error.
Why I see 2 times the method of B called? This one is funny. To call a virtual function of an object, compiler delegates the decision which method exactly should be called to a virtual table (it's address occupies the first 8 byte of such an object (at least for my compiler and 64bit)). A not that well known details about virtual methods is that during the destructor-call all virtual methods are called as if they were not virtual. But what has it to do with your code? You see its side-effect: The non-virtual behavior is ensured in the destructor by overwriting the virtual table of the current object by the virtual table of the current class. So after the destructor of B is called, the memory contains a virtual table of the class B which you can see, because B::method is called twice.
Let's track the value of the virtual table it in your program:
call of A{}: At first the superclass B-constructor is called - the (not yet fully finished) object has the virtual table of class B (this address is moved into the first 8 byte occupied by the object), than A-constructor is called - now the object has the virtual table of class A.
call of ~A(): after its execution, the destructor of A automatically calls the destructor of B. The first thing the destructor of B does is to overwrite the virtual table of the object with the virtual table of the class B.
So after the destruction the memory is still there and interpreted as an object would have the the virtual table of class B.
itr->method(); finds the virtual table of class B at the address itr points to and calls B::method().

Order of the destructor calls at the end of block\program [duplicate]

This question already has answers here:
Order and point of calling destructor
(4 answers)
Closed 9 years ago.
So at the end of the block\program the compiler calls on it's own the destructors for the objects that were defined. Is there a particular order in which the destructors are called?
class Foo1{
public:
~Foo1 () {cout << "Foo1 DTOR" << endl;}
};
class Foo2{
public:
~Foo2 () {cout << "Foo2 DTOR" << endl;}
};
void main(){
Foo1 A;
Foo2 B;
}
running this program I had the output:
Foo2 DTOR
Foo1 DTOR
Is it how it always works starting from the last defined object and ending with the first one? Or this behavior ca not be predicted and my output is something particular to this situation?
Destructors are always run in the reverse order to constructors (except dynamic memory where programmer explicitly deletes objects in memory (with calling it's destructor)).
In you example A is places before B, so it's constructor called earlier. That's why it's destructor was called after B's destructor.
LIFO ordering for object lifetimes is the only thing that makes sense. Consider this moderately representative example:
struct ValueHolder
{
int value;
ValueHolder() : value(0) { }
~ValueHolder() { std::cout << "Value = " << value << "\n"; }
};
struct HolderGuard
{
ValueHolder & h;
HolderGuard(ValueHolder & vh) : vh(h) { }
~HolderGuard() { ++h.value; }
};
Usage:
int main()
{
ValueHolder h;
HolderGuard(h);
}
This will first increment the held value, and then print it. It would be impossible for later things to depend on earlier things if the later things weren't destroyed first.
(The beauty of the example construction is that it does the right thing even when later code throws an exception.)

How to prove that Copy Constructor is mandatory

I Have just created a class with an integer variable and a pointer variable. After creating its object , I passed it to a function. Even after returning the function the program is not throwing the exception
#include"iostream"
using namespace std;
class A
{
public :
int i;
char *c;
void show();
};
void func(A obj);
int main()
{
A a;
a.i = 10;
a.c = "string";
cout << " Before Fun " << endl;
a.show();
cout << " Going To Call func " << endl;
func(a);
cout << " After func " << endl;
a.show();
return 0;
}
void A::show()
{
cout << " The valuses in Object are " << i << '\t' << c << endl;
}
void func(A aa)
{
cout << " The valuses in Object are " << aa.i << '\t' << aa.c << endl;
}
In The Func I am passing the object a (from main) and it would get copied in aa (stack of func). so after returning from the func if i call show ( the pointer c would be null of a), It would give me exception
But it is not happening . please help me to prove the requirement of copy constructor
Hide the copy constructor. That will cause a compilation error everywhere it is called implicitly.
class A
{
public :
int i;
char *c;
private:
A(const A& _other);
};
If no copy constructor is declared for an object, one is implicitly defined. This copy constructor copies each element of the object.
In your example, the call to func(a) will call this copy constructor, and so aa will be a copy of a (aa.i will be 10 and aa.c will point to the first element of "string").
If you are using C++11 you can do the following to remove the copy constructor
class A
{
public :
int i;
char *c;
void operator=(const A& _other) = delete;
A(const A& _other) = delete;
};
or even better:
class A : public NonCopyable // perhaps std:: or if you prefer boost, boost::
{
public :
int i;
char *c;
};
http://en.wikipedia.org/wiki/C++11#Explicitly_defaulted_and_deleted_special_member_functions
When you make a class, a null constructor and copy constructor exist implicitly.
So that is why it does not throw an exception.
However, if you define ANY constructor, you will then need to define others otherwise the rest of the constructors will be overwritten.
For example, you define a null constructor only. Then it will throw an exception. Because the implicitly defined copy constructor will be overridden.
This is one way of proving the need of a copy constructor.
An implicit copy constructor does exist if you do not define one explicitly. It is called in your func() function. A object is copied and assigned a value for its member i.
Result will be: that you do get with show() the value for i that you had before when calling func. This is with no surprise because you are not doing any assignment to members of A inside A.
Implicit copy constructor by the compiler provide member-wise copy. This is what you may need in most cases.
When is default constructor not sufficient ? you have pointer like members, and need a deep-copy of it. You don't want to copy the pointer (what copy constructor would do), but rather to have the object pointed to copied. But why do you need deep copy ? You don't want to copy the pointer (which is owned by any instance of the class), and end up calling twice destructor on the same pointer. From the second call to delete on this pointer, heap corruption ensues. You may also need copy constructor made explicit for shared_pointers.
Note that, for performance reasons, it is best pass object by const reference than by value.
In your case the copy constructor provided by compiler is present.
Modify your code and write a copy constructor as:
//Default and copy constructor
A()
{
i = 0;
c = NULL;
}
A(const A& _other)
{
cout<<"In copy cons"<<endl;
}
When you will modify the code as per above when func gets called then your own copy constructor gets called in this case you will get the junk values(can not predict)
And if you modify your copy constructor code as
A(const A& _other)
{
cout<<"In copy cons"<<endl;
i = _other.i;
c = new char [(strlen(_other.c) +1)];
strcpy(c,_other.c);
}
Now you can see the differnce in both outputs and the use of Copy constructor how and where it's used.

Is `new (this) MyClass();` undefined behaviour after directly calling the destructor?

In this question of mine, #DeadMG says that reinitializing a class through the this pointer is undefined behaviour. Is there any mentioning thereof in the standard somewhere?
Example:
#include <iostream>
class X{
int _i;
public:
X() : _i(0) { std::cout << "X()\n"; }
X(int i) : _i(i) { std::cout << "X(int)\n"; }
~X(){ std::cout << "~X()\n"; }
void foo(){
this->~X();
new (this) X(5);
}
void print_i(){
std::cout << _i << "\n";
}
};
int main(){
X x;
x.foo();
// mock random stack noise
int noise[20];
x.print_i();
}
Example output at Ideone (I know that UB can also be "seemingly correct behaviour").
Note that I did not call the destructor outside of the class, as to not access an object whose lifetime has ended. Also note, that #DeadMG says that directly calling the destructor is okay as-long-as it's called once for every constructor.
That would be okay if it didn't conflict with stack unwinding.
You destroy the object, then reconstruct it via the pointer. That's what you would do if you needed to construct and destroy an array of objects that don't have a default constructor.
The problem is this is exception unsafe. What if calling the constructor throws an exception and stack is unwound and the destructor is called for the second time?
{
X x;
x.foo(); // here ~X succeeds, then construction fails
} //then the destructor is invoked for the second time.
That aspect specifically would be undefined behavior.
Apart from #sharptooth's answer. I am just wondering for 2 more cases. At least they are worth mentioning.
(1) If the foo() was invoked using a pointer on heap which was allocated using malloc(). The constructor is not called. Can it be safe ?
(2) What if the derived class is calling foo(). Will it be a good behavior ? e.g.
struct Y : X {}; // especially when there is virtual ~X()
int main ()
{
Y y;
y.foo();
}

Meaning of "~" (tilde) symbol in C++?

// AirlineTicket.h
class AirlineTicket
{
public:
AirlineTicket();
~AirlineTicket();
int getNumberOfMiles();
private:
int mNumberOfMiles;
};
I want now what is the meaning of ~AirlineTicket(); in this code?
I don't know the meaning of ~ (tilde).
It is the destructor.
It gets called when you destroy (reaching end of scope, or calling delete to a pointer to) the instance of the object.
In the context you're using it, it defines a destructor.
In other context such as the following one, it's also called bitwise negation (complement):
int a = ~100;
int b = ~a;
Output: (ideone)
-101
100
~ signs that it is a destructor and when ever the object goes out of scope, corresponding destructor is called.
When the destructor is called ?
Taking an example -
#include <iostream>
class foo
{
public:
void checkDestructorCall() ;
~foo();
};
void foo::checkDestructorCall()
{
foo objOne; // objOne goes out of scope because of being a locally created object upon return of checkDestructorCall
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
}
int main()
{
foo obj; // obj goes of scope upon return of main
obj.checkDestructorCall();
return 0;
}
Results on my system:
Destructor called 0xbfec7942
Destructor called 0xbfec7943
This example just serves to indicate when a destructor is called. But destructor is written only when the class manages resources.
When class manages resources?
#include <iostream>
class foo
{
int *ptr;
public:
foo() ; // Constructor
~foo() ;
};
foo:: foo()
{
ptr = new int ; // ptr is managing resources.
// This assignment can be modified to take place in initializer lists too.
}
foo:: ~foo()
{
std::cout << "Destructor called \t" << this << "\n";
delete ptr ; // Returning back the resources acquired from the free store.
// If this isn't done, program gives memory leaks.
}
int main()
{
foo *obj = new foo;
// obj is pointing to resources acquired from free store. Or the object it is pointing to lies on heap. So, we need to explicitly call delete on the pointer object.
delete obj ; // Calls the ~foo
return 0;
}
Results on my system:
Destructor called 0x9b68008
And in the program, you posted I don't see a need to write destructor. Hope it helps !
It's the class destructor. You might want to pick up an introductory text on C++ development, as destructors are a fundamental concept in OOP. There is a good reference site here, and the C++ FAQ is another good resource.
~AirlineTicket(); is the destructor for the class AirlineTicket
see this link for further reference
The destructor is called when you delete the object of that class, to free any memory allocated or resources being used by the object.
~ introduces a destructor. It's used because (a) it was available, ad (b) ~ is one (of several) mathematical notation for "not".
This indicates destructor of class.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr380.htm