创建具有默认构造函数的未初始化项数组
Creating an uninitialized array of items which have default constructors?
给定一个类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;
。在 Rust 中也是如此:
let mut foos: [Foo; 20000] = unsafe { std::mem::uninitialized() };
如果使用 C++11
,则可以使用 std::vector
和 emplace_back()
vector<Foo> foos;
for(int i = 0; i < 20000; ++i)
foos.emplace_back( /* arguments here */);
也许这更准确地回答了手头的问题?
#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();
您可能
正在寻找的是std::get_temporary_buffer
:
int main()
{
size_t n = 20000;
auto buf = std::get_temporary_buffer<Foo>(n);
if (buf.second<n) {
std::cerr << "Couldn't allocate enough memoryn";
return EXIT_FAILURE;
}
// ...
std::raw_storage_iterator<Foo*,Foo> iter(buf.first);
for (int i = 0; i < n; ++i) {
*iter++ = Foo();
}
// ...
std::return_temporary_buffer(buf.first);
}
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组