【发布时间】:2021-03-02 18:10:16
【问题描述】:
我可以使用选项 3 实现我需要的功能,但是我想调查是否可以在堆栈上创建数组。
#include <array>
#include <vector>
struct NotDefaultConstructable
{
NotDefaultConstructable(int val){};
};
int main()
{
//std::array<NotDefaultConstructable, 5> aA; // Fails to compile. [On stack]
//std::vector<NotDefaultConstructable> aV(5); // Fails to compile. [On heap]
std::vector<NotDefaultConstructable> aV; // Compiles. [ On heap]
aV.reserve(5);
}
【问题讨论】:
-
它可以编译,因为
aV是一个 empty 向量。aV.reserve(5)不会使其成为 5 的向量NotDefaultConstructables -
选项 3 正在创建一个空的“数组”。它不包含任何对象。所以不清楚你到底在追求什么。
-
@Harry
NotDefaultConstructable aV[5]也不起作用:godbolt.org/z/8MvxTo -
您的选项 1,2 和 3 都非常不同,因此您需要说明您想要实现的功能。仅从代码中尚不清楚。 (选项 3 不创建任何
NotDefaultConstructable对象顺便说一句) -
@AidanGallagher 我认为你的对象的生命周期管理会像那样糟糕; godbolt.org/z/54q9o1 - 这是一种做你想做的事的方式,但你需要自己显式地构造和销毁对象
标签: c++ arrays constructor