例如,我有 A 类:
class A{
int value_;
public:
A(A& a){
value_ = a.value_;
}
A(int value){
value_ = value;
}
};
我想要一个 A 类 vector ,但我想将所有 vector 的值传递给 A(int value)
。
std::vector<A,allocator<A>> my_vector;
- 最好的方法是什么?
- 有没有办法使用分配器?
最佳答案
c++11With the new standard added functionality was granted to objects of Allocator type.
One of the features added was that Allocators now allows emplacement construction, aka. construction of objects using a constructor other than copy/move.
template< class U, class... Args > void construct( U* p, Args&&... args );
The standard does guarantee that STL containers must use this new feature, and with that said you could implement your own allocator just for the purpose of default initializing a non-default-initializable object.
It's not the prettiest solution, but whatever floats your boat..
c++03The allocator has nothing to do with that part of object initialization, it's only purpose is to allocate/deallocate memory, the type of initialization you are referring to is done elsewhere.
The only constructor an allocator will call is the copy-constructor when someone asks it to perform a placement-new, and the value passed to that copy-ctor has already been established somewhere else.
To sum things up; No, you cannot use an allocator so solve this particular problem.
std::vector 什么时候需要使用default-ctor?
std::vector
仅在两种情况下使用它拥有的类型的默认构造函数:
您指定
std::vector
的元素数量在适当的构造函数重载中,但不提供默认值您使用
std::vector<T>::resize (n)
并增加容器中对象的数量(注意没有指定成员函数的第二个参数)
考虑到上述内容,我们可以使用容器做很多事情,而无需在我们的对象中提供默认构造函数,例如将其初始化为包含 N 个值为 X 的元素.
struct A{
A (A const& a)
: value_ (a.value_)
{ }
A (int value)
: value_ (value)
{}
int value_;
};
int
main (int argc, char *argv[])
{
std::vector<A> vec (5, A(1)); // initialize vector with 5 elements of A(1)
vec.push_back (A(3)); // add another element
}
但是我真的很想能够使用vec.resize()!?
然后你有二、三、四个选项:
使用分配器的 C++11 方法
让你的对象有一个默认构造函数
用一个非常薄的包装器包装您的对象,其唯一目的是默认初始化包含的对象(这在某些情况下说起来容易做起来难)
“在 boost::optional 中包装 [对象] 实际上可以为任何类型提供默认构造函数” - @ Xeo
关于c++ - 如何初始化STL容器中存在的类的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502601/