For example, I have class A:
class A{
int value_;
public:
A(A& a){
value_ = a.value_;
}
A(int value){
value_ = value;
}
};
I want a vector of class A but I’d like to pass a value to A(int value) for all of them.
std::vector<A,allocator<A>> my_vector;
- What is the best way to do it?
- Is there a way by using allocator?
when does std::vector require the use of a default-ctor?
std::vectoronly uses the default-constructor of the type it holds in two situations:You specify the number of elements of your
std::vectorin the appropriate constructor overload but doesn’t supply a default valueYou use
std::vector<T>::resize (n)and increase the number of objects in the container (note the lack of specifying the 2nd argument to the member-function)With the above in mind we can do plenty of things using the container without supplying a default constructor in our object, like initializing it to contain N elements of value X.
But I really want to be able to use vec.resize ()!?
Then you have
two,three, four options:Go with the C++11 approach of using Allocators
make your object have a default constructor
wrap your object with a very thin wrapper who’s only purpose is to default initialize the containing object (this might be easier said then done in some circumstances)
"Wrapping [the object] in boost::optional practically gives any type a default ctor" – @Xeo