We can call destructor explicitly through class pointer, why not constructor? Any idea?
#include <iostream>
class Con {
public:
Con( int x ) : x( x ) {
}
private:
int x;
};
int main() {
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
c->~Con(); // ok!
delete c;
}
Thanks,
A pointer does not refer to any object until you provide it with an address; therefore, no constructor is called.
If you had a pointer to a constructor it would either have to be a static pointer, something like a factory function, or a special pointer to something that would be called immediately after memory allocation. It could not be an ordinary member function and still work as a constructor.
No this is not possible. You cannot assign to this.
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
You can actually call it, it is just that the syntax is not that of calling a member method (of which the destructor is an special case), so it is not done with the member access operators. Rather you have to resort to the placement-new syntax:
Con c;
c.~Con(); // destroy, now c is not a Con anymore
new (&c) Con(); // recreate, now c is a Con again
As a particular case, in the C++0x proposal, that is actually used in one of the code examples, providing means to reuse a union
as a different type in the event of an union containing non-POD elements:
union U {
int i;
float f;
std::string s;
};
int main() {
U u;
new (&u.s) std::string( "foo" );
u.s.~string();
u.i = 5;
}
}
No. You cannot.
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
You've already called the constructor in the new
expression.
By the time you've a valid pointer of type Con*
, you've already created an object. And calling constructor on the "constructed" object doesn't even make sense. So why would C++ allow that?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With