Rod*_*ddy 7 c++ boost stl vector
我有一个类,是inhenerently不可复制的(一个线程,所以没有拷贝语义意义),我想有这些的largeish"阵",具有非默认构造函数构造相同.请注意,该数组是固定大小.
我只能使用带有C++数组的默认构造函数,除非我单独初始化每一个.
Thread myArray[128]; // uses default constructor - wrong
Run Code Online (Sandbox Code Playgroud)
我可以明确地列出对象构造函数和参数,但这很冗长和丑陋
Thread myArray[128] = { Thread(params,...), Thread(params,...), ... x 128 ; // ugly
Run Code Online (Sandbox Code Playgroud)
似乎我不能使用stl向量,因为该对象是不可复制的 - 虽然向量永远不会改变大小.我猜构造函数实际上是在复制!
std::vector<Thread> myVector(128, Thread(params,...));// won't compile
Run Code Online (Sandbox Code Playgroud)
我这样做的方式是使用一系列智能指针和一个初始化循环,但也许我错过了一些东西:
还有其他方式 - 可能是使用增压容器,还是使用不同的容器类型?
这可能看起来很疯狂(可能是),但......
struct ThreadInitValues{
// your actual params
int i;
float f;
};
struct Thread{
Thread(int i = _init.i, float f = _init.f)
: _i(i)
, _f(f)
{}
static ThreadInitValues _init;
private:
// uncopyable
Thread(Thread const&);
Thread& operator=(Thread const& other);
// your actual member
int _i;
float _f;
};
ThreadInitValues Thread::_init;
int main(){
Thread::_init.i = 5;
Thread::_init.f = 3.14f;
Thread arr[128];
}
Run Code Online (Sandbox Code Playgroud)
也许这适合你.:)当然,您现在需要注意数组是否在多线程代码本身中初始化...
智能指针向量,每个实例都是动态分配的,绝对是最简单的方法。否则(我只会在绝对必要时才这样做),您可以或多或少地模仿std::vector内部的操作。大致如下:
union
{
double just_to_ensure_alignment;
unsigned char data[ sizeof(Thread) * elementCount ];
} array;
// construct...
for ( int i = 0; i != elementCount; ++ i )
new (data + i * sizeof(Thread)) Thread(params,...);
// access...
Thread& getAt( int i )
{
return reinterpret_cast<Thread*>( data + i * sizeof(Thread) );
}
Run Code Online (Sandbox Code Playgroud)
(我实际上会将其包装在一个类中,如果只是为了能够使用
operator[]而不是getAt。)