Bojack
Bojack

Reputation: 479

vector of class without default constructor

Consider the following class:

Class A
{
    public:
       A() = delete;
       A(const int &x)
       :x(x)
       {}
    private:
       int x;
};

How can one create an std::vector<A> and give an argument to the constructor A::A(const int&)?

Upvotes: 21

Views: 21703

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254621

How can I create a std::vector of type A and give an argument to A's constructor?

std::vector<A> v1(10, 42);  // 10 elements each with value 42
std::vector<A> v2{1,2,3,4}; // 4 elements with different values

How would I add 3 to the vector?

v.emplace_back(3);          // works with any suitable constructor
v.push_back(3);             // requires a non-explicit constructor

The lack of a default constructor only means you can't do operations that need one, like

vector<A> v(10);
v.resize(20);

both of which insert default-constructed elements into the vector.

Upvotes: 29

Quentin
Quentin

Reputation: 63144

Templates are not instantiated in one go : they only instantiate what is needed. A satisfies all the conditions for the following (constructing an empty vector) to be valid :

std::vector<A> v;

However, as A does not have a default constructor, the following (creating a vector with default-initialized content) would fail :

std::vector<A> v(100);

And that's a good thing. However, valid methods will be instantiated fine :

v.emplace_back(42);

Upvotes: 7

pmr
pmr

Reputation: 59831

The trick is in how you add elements into the vector and what member functions of the vector you use.

std::vector<A> v;
v.emplace_back(3);

Upvotes: 3

Related Questions