Can you invoke an instantiated object's class constructor explicity in C++?

前端 未结 7 2249
逝去的感伤
逝去的感伤 2020-12-31 15:17

After creating a instance of a class, can we invoke the constructor explicitly? For example

class A{
    A(int a)
    {
    }
}

A instance;

instance.A(2);
         


        
7条回答
  •  渐次进展
    2020-12-31 15:32

    By the way, this sounds like a design flaw. Once an object is constructed there should never be a need to re-construct it. Such variable name reuse makes the code rather harder to understand. For that reason, making constructor-like functionality available through an extra function init or set is often wrong (but sometimes unavoidable).

    As Michael said, placement new could be used here but is really intended for different uses. Also, before constructing a new object in a memory location, you have to explicitly destroy the old object:

    instance.~A();
    

    Also, placement new can have an averse effect on your memory because overloads might expect that the memory it is passed belongs to the heap! In conclusion: don’t. do. this.

    EDIT To demonstrate that calling the destructor is really necessary (for non-POD), consider the following example code:

    #include 
    
    struct A {
        A(int a) { std::cerr << "cons " << a << std::endl; }
        ~A() { std::cerr << "dest" << std::endl; }
    };
    
    int main() {
        A instance(2);
        new (&instance) A(3);
    }
    

    As expected, the program results in the following output:

    cons 2
    cons 3
    dest
    

    … which means that the destructor for the first object is not called. The same goes for any resources that A might have acquired.

提交回复
热议问题