Emplacing in vector using default constructor

Chizzy C picture Chizzy C · Nov 21, 2014 · Viewed 14.1k times · Source

I want to use vector::emplace to default construct a non-copyable and non-assignable object and then use specific methods on the object using an iterator to the newly created object. Note that there are no parameterized constructors of the class just the default constructor. A simple example is:

#include <iostream>
#include <vector>
using namespace std;

class Test {
public:
    Test() {}
private:
    Test(const Test&) = delete;             // To make clas un-copyable.
    Test& operator=(const Test&) = delete;

    int a_;
};

int main() {
    vector<Test> test_vec;
    test_vec.emplace_back();     // <---- fails

    return 0;
}

vector::emplace() constructs a new object but requires arguments to a non-default constructor. vector::emplace_back() will construct at the end of the vector.

Is there a way to emplace with default construction. Is there a way to use piecewise construction or default forwarding perhaps using std::piecewise_construct as there is for maps? For example, in the case of maps, we can use:

std::map<int,Test> obj_map;
int val = 10;
obj_map.emplace(std::piecewise_construct,
                std::forward_as_tuple(val),
                std::forward_as_tuple());

Is there something similar for vectors?

Answer

Columbo picture Columbo · Nov 21, 2014

vector::emplace_back() will construct at the end of the vector but also require arguments.

Parameter packs can be empty. Thus the variadic template emplace_back can be called without arguments; I.e.

vector<VeryLimitedClass> vec;
vec.emplace_back();

Is valid code that initializes an object of type VeryLimitedClass through its default constructor and "emplaces" it at the back of vec.