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

前端 未结 7 2242
逝去的感伤
逝去的感伤 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:41

    You can use placement new, which permits

    new (&instance) A(2);
    

    However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do

    A instance(2);
    

    Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.

提交回复
热议问题