我想使用vector::emplace
默认构造一个不可复制和不可分配的对象,然后使用迭代器对新创建的对象使用对象上的特定方法。请注意,该类没有参数化构造函数,只有默认构造函数。一个简单的例子是:
#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()
构造一个新对象,但需要非默认构造函数的参数。vector::emplace_back()
将在向量的末尾构造。
有没有办法使用默认构造进行替换。有没有办法使用分段构造或默认转发,也许std::piecewise_construct
像地图一样使用?例如,在地图的情况下,我们可以使用:
std::map<int,Test> obj_map;
int val = 10;
obj_map.emplace(std::piecewise_construct,
std::forward_as_tuple(val),
std::forward_as_tuple());
向量有类似的东西吗?