How to initialize an array of objects of a parameterized constructor

前端 未结 3 677
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 10:26

I need to initialize an array of objects of a parametrized constructor . How can i do it in best possible way ?

   # include
   # include&l         


        
3条回答
  •  花落未央
    2021-01-03 11:05

    Note that malloc does not construct objects, and so calling a1[i]=a2 is bad form. It probably seems to work fine since they are POD-ish objects, but this is not the proper way to do C++. It is undefined behavior, which is completely unpredictable. It may work ten thousand times in a row, and then erase your bank account. You should use new instead, which also constructs. Or better yet, use a vector, like the other answers suggest. Also, be sure that the default constructor initializes the data, and initialization will be less of a worry.

    If you really must use malloc, the "correct way" to initialize is this:

    std::uninitialized_copy(a1, a1+10, a2); //constructs and assigns
    

    which is roughly equivalent to:

    {
        int i=0;
        try {
            for(i=0; i<10; ++i)
               new(a1+i)A(a2); //constructs and initializes in the buffer
        } catch(...) { 
            try {
                for(; i>=0; --i)
                   (a1+i)->~A(); //destroy if an error occured
            } catch(...) { 
                std::terminate();
            }
            throw;
        }
    }
    

提交回复
热议问题