简体   繁体   English

将构造函数传递给指针数组

[英]Passing a constructor to array of pointers

I have always been using vectors for storing objects when a list type container is required. 当需要列表类型的容器时,我一直使用矢量来存储对象。 I wanted to know how you can pass constructors to array pointers.The following works in C++03 if the object foo did not have a constructor 我想知道如何将构造函数传递给数组指针。如果对象foo没有构造函数,则以下内容在C ++ 03中有效

foo* p = new foo[5]()

Now what if the constructor of foo required an int how would I pass the constructor in the above statement? 现在,如果foo的构造函数需要一个int ,我该如何在上面的语句中传递该构造函数呢?

It is not possible. 这不可能。 Your foo instances can only be default-constructed. 您的foo实例只能是默认构造的。

UPDATE 1 更新1

If your foo does not have a default constructor then you will get a compiler error either about use of deleted function or about no matching ctor. 如果您的foo没有默认的构造函数,则将收到有关使用已删除函数或没有匹配ctor的编译器错误。

UPDATE 2 更新2

I see that others offer C++11 solution. 我看到其他人提供了C ++ 11解决方案。 My answer appears to be correct only for C++03 or earlier. 我的答案似乎仅对C ++ 03或更早版本是正确的。

Since C++11, you can use brace initializers: 从C ++ 11开始,您可以使用大括号初始化程序:

foo * p = new foo[5] { 1, 2, 3, 4, 5 };   // better: "auto p = ..."

This assumes that foo is implicitly constructible from int . 假设foo是可以从int 隐式构造的。

But you can just as well use containers: 但是您也可以使用容器:

std::vector<foo> v { 1, 2, 3 };
std::list<foo> w { 1, 2, 3 };

Or perhaps: 也许:

std::unique_ptr<foo[]> q(new foo[4] { 1, 2, 3, 4} );

how would I pass the constructor in the above statement? 我如何在上面的语句中传递构造函数?

new[] does not have a form for forwarding constructor parameters. new[]没有用于转发构造函数参数的形式。

You would instead call the constructors yourself. 您可以自己调用构造函数。

foo* p = new foo[5]{ foo(1), foo(2), foo(3), foo(4), foo(5) };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM