No array allocated using new can have an initializer?

狂风中的少年 提交于 2019-12-10 01:45:43

问题


In the book I am reading at the moment (C++ Complete Reference from Herbert Schildt), it says that no array allocated using new can have an initializer.

Can't I initialize a dynamically allocated array using new? If not whats the reason for it?


回答1:


That's not quite true (you should almost certainly get yourself an alternative reference), you are allowed an empty initializer (()) which will value-initialize the array but yes, you can't initialize array elements individually when using array new. (See ISO/IEC 14882:2003 5.3.4 [expr.new] / 15)

E.g.

int* p = new int[5](); // array initialized to all zero
int* q = new int[5];   // array elements all have indeterminate value

There's no fundamental reason not to allow a more complicated initializer it's just that C++03 didn't have a grammar construct for it. In the next version of C++ you will be able to do something like this.

int* p = new int[5] {0, 1, 2, 3, 4};



回答2:


The book is correct; you cannot have,

int *p = new int[3](100);

There is no understandable reason behind it. That's why we have initializers for array in C++0x.




回答3:


I think the book is correct, in generally you cannot do that with current version of c++. But you can do that with boost::assign to achieve a dynamic array, see below

#include <boost/assign/list_of.hpp>
class Object{
public:
    Object(int i):m_data(i){}
private:
    int m_data;
};

int main()
{
    using namespace boost::assign;
    std::vector<Object> myvec = list_of(Object(1))(Object(2))(Object(3));
}


来源:https://stackoverflow.com/questions/6717246/no-array-allocated-using-new-can-have-an-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!