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

后端 未结 9 598
隐瞒了意图╮
隐瞒了意图╮ 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 <typename T, typename... Args>
    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);
    
    0 讨论(0)
  • 2020-12-02 11:05

    Yes, when you've got your own allocated buffer you use placement new. Brian Bondy has a good response here in a related question:

    What uses are there for "placement new"?

    0 讨论(0)
  • 2020-12-02 11:15

    I think you're looking for Placement New. The C++ FAQ Lite has a good summary of how you do this. There are a few important gotchas from this entry:

    1. You're supposed to #include <new> to use the placement new syntax.
    2. Your memory buffer needs to be properly aligned for the object you are creating.
    3. It's your job to manually call the destructor.
    0 讨论(0)
提交回复
热议问题