给定一个类Foo,它具有一些值初始化默认构造函数:
class Foo {
private:
uint32_t x;
public:
constexpr Foo()
: x { 3 }
{}
// ... and some other constructors
};我需要分配这些Foo的数组,我不希望数组的默认构造函数运行,因为以后我将显式地初始化每个元素。就像这样:
Foo foos[20000];
for (int i = 0; i < 20000; ++i) {
foos[i] = init(i);
}考虑到我们不允许将Foo的默认构造函数更改为非初始化的构造函数,是否有一种方法可以获得这样一个未初始化的Foo数组?
顺便说一句,这就是如何在D中创建一个未初始化的数组:
Foo[20000] foos = void;...and在锈蚀中也是一样的:
let mut foos: [Foo; 20000] = unsafe { std::mem::uninitialized() };发布于 2015-03-12 03:00:41
也许这能更准确地回答眼前的问题?
#include <type_traits>
class Foo {
private:
uint32_t x;
public:
constexpr Foo()
: x { 3 }
{}
constexpr Foo(uint32_t n)
: x { n * n }
{}
};
// ...and then in some function:
typename std::aligned_storage<sizeof(Foo), alignof(Foo)>::type foos[20000];
for (int i = 0; i < 20000; ++i) {
new (foos + i) Foo(i);
}缺点似乎是,您只能使用构造函数来初始化这些元素,而不能使用空闲函数或其他任何东西。
问:那么我能像这样访问那些Foo吗?
Foo* ptr = reinterpret_cast<Foo*>(foos);
ptr[50] = Foo();发布于 2015-03-12 01:40:46
如果您使用C++11,您可以使用std::vector和emplace_back()
vector<Foo> foos;
for(int i = 0; i < 20000; ++i)
foos.emplace_back( /* arguments here */);https://stackoverflow.com/questions/29000519
复制相似问题