4

Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines of code in object's and its parents' constructors...

class MyClass()
{
    MyClass() { }
    virtual ~MyClass();

    void reset()
    {
         this->~MyClass();
         this->MyClass::MyClass(); //error: Invalid use of MyClass
    }
};
Ryan
  • 1,451
  • 2
  • 27
  • 36
  • 7
    If there are thousands of lines of code in ANY function, something is very wrong somewhere. –  May 17 '11 at 14:18

3 Answers3

5

You can still move construction/destruction into separate functions and call those directly. i.e.

class MyClass {
public:
    MyClass() { construct(); }
    ~MyClass() { destruct(); }

    void reset() {
        destruct();
        construct();
    }

private:
    void construct() {
        // lots of code
    }

    void destruct() {
        // lots of code
    }
};
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • Thank you very much, everybody! I can't believe I could have missed this solution... – Ryan May 17 '11 at 13:53
3

You could use placement new syntax:

this->~MyClass(); // destroy
new(this) CMyClass(); // construct at the same address
sharptooth
  • 167,383
  • 100
  • 513
  • 979
2

A constructor is called using placement new

new (address) MyClass();

This constructs a MyClass in an empty space at address.

Would never do this inside the class though!

Edit
If you already have an object of the right type, and want to assign it default values, an alternative is

*this = MyClass();

which creates a new object with default values and assigns that value to your existing object.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • The problem is that MyClass is always being created on stack – Ryan May 17 '11 at 13:39
  • @Ryan: If you do it as @sharptooth shows, then it will be no memory leak, as you already have the memory. – Xeo May 17 '11 at 13:41