How do I declare an array of objects whose class has no default constructor?

后端 未结 13 1122
时光取名叫无心
时光取名叫无心 2020-11-30 06:25

If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class



        
13条回答
  •  余生分开走
    2020-11-30 06:49

    The proper way is use to std::aligned_storage. You will have to manually construct and destruct items as well as reintrepret_cast when you want to access an item. I recommend you write a small wrapper class around storage_t to take care of this. Someone mentioned using boost::optional which uses a bool and a storage_t under the hood. This method saves you a bool.

    template
    using storage_t = typename std::aligned_storage::type;
    
    struct Foo;
    
    size_t i = 55;
    storage_t items[1000]; // array of suitable storage for 1000 T's
    new (reintrepret_cast(items + i)) Foo(42); // construct new Foo using placement new
    *reintrepret_cast(items + i) = Foo(27);    // assign Foo
    reintrepret_cast(items + i)->~Foo()        // call destructor
    

提交回复
热议问题