Object array initialization without default constructor

后端 未结 11 1923
误落风尘
误落风尘 2020-11-22 04:20
#include 
class Car
{
private:
  Car(){};
  int _no;
public:
  Car(int no)
  {
    _no=no;
  }
  void printNo()
  {
    std::cout<<_no<

        
11条回答
  •  伪装坚强ぢ
    2020-11-22 04:43

    You can use placement-new like this:

    class Car
    {
        int _no;
    public:
        Car(int no) : _no(no)
        {
        }
    };
    
    int main()
    {
        void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
        Car *ptr = static_cast(raw_memory);
        for (int i = 0; i < NUM_CARS; ++i) {
            new(&ptr[i]) Car(i);
        }
    
        // destruct in inverse order    
        for (int i = NUM_CARS - 1; i >= 0; --i) {
            ptr[i].~Car();
        }
        operator delete[](raw_memory);
    
        return 0;
    }
    

    Reference from More Effective C++ - Scott Meyers:
    Item 4 - Avoid gratuitous default constructors

提交回复
热议问题