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?
As pointed out by @dyp and @Casey in the comments,
std::emplace
will not work for vectors of the Test class as the class is neither movable nor copyable because "the user-declared copy constructor suppresses generation of the default move constructor" (@Casey).To use
emplace
here, the class will need to be movable or copyable. We can make the class movable by explicitly defining (and defaulting) the move constructors:This will also implicitly make the class not-copyable "since declaring the move operations will suppress implicit generation of the copies." (@Casey)
Now we can use
std::emplace_back()
and then usevector::back()
to call methods of the newly created object.