如何初始化一系列不可移动,不可复制的对象? [英] How to initialize a sequence of non-movable, non-copyable objects?
问题描述
假设我有一个既不可移动也不可复制的类型:
Let's say I have a type which is neither movable nor copyable:
struct foo
{
explicit foo( size_t ){}
~foo(){}
foo( foo const & ) = delete;
foo( foo && ) = delete;
foo& operator=( foo const & ) = delete;
foo& operator=( foo & ) = delete;
};
现在给定编译时已知的数字(称为N)在堆栈上创建一个序列,每个序列用数字0到N-1初始化?我会满意一个C风格的数组 foo [N]
, std :: array< foo,N>
,或者甚至可以是某种 std :: tuple
。
Now given a number known at compile time (call it N), is there any way that I can create a "sequence" of these on the stack with each one initialized with numbers 0 through N-1? I would be satisfied with a C-style array foo[N]
, a std::array< foo, N >
, or perhaps even a std::tuple
of some kind.
我想避免的是写出:
foo f0( 0 ), f1( 1 ), ... fNminus1( N-1 );
当感觉这是编译器应该能为我做的事情。我已经能够想出的最好的是使用 boost :: optional
。
when it feels like this is something the compiler should be able to do for me. The best I've been able to come up with is using boost::optional
.
boost::optional< foo > f[N];
for( size_t i = 0U; i < N; ++i )
f[i] = boost::in_place( i );
但这依赖于运行时逻辑,即使所有必需的信息在编译时可用。另外,我还剩下一些类似指针数组的东西。
But that relies on runtime logic even though all the required information is available at compile-time. Plus, I'm left with something that behaves like an array of pointers.
推荐答案
// create a type with the proper alignment
typedef std::aligned_storage<sizeof(foo), std::alignment_of<foo>::value>::type buffer_type;
const int N = 10;
// create an array of uninitialized raw data
buffer_type storage_buffer[N];
// initialize each foo object with placement new
for (size_t i=0; i<N; ++i)
new (storage_buffer + i) foo(i);
foo * fp = (foo*)(&storage_buffer);
// access your foo objects via fp
// you must manually call the destructor of each object
for (size_t i=0; i<N; ++i)
fp[i].~foo();
如果这看起来很麻烦,那就是。但你可以很容易地把这个功能封装在一个类中。
If that seems like a lot of hassle, it is. But you could easily encapsulate that functionality in a class.
这篇关于如何初始化一系列不可移动,不可复制的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!