C++, is it possible to call a constructor directly, without new?

后端 未结 9 621
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 10:40

Can I call constructor explicitly, without using new, if I already have a memory for object?

class Object1{
    char *str;
public:
    Object1(c         


        
9条回答
  •  时光取名叫无心
    2020-12-02 11:04

    You can use the following template

    template 
    inline void InitClass(T &t, Args... args)
    {
        t.~T();
        new (&t) T(args...);
    }
    

    usage:

    struct A
    {
       A() {}
       A(int i) : a(i) {}
       int a;
    } my_value;
    
    InitClass(my_value);
    InitClass(my_value, 5);
    

提交回复
热议问题