编辑:
在这个线程中讨论的三种形式中,避免不必要复制的一种是@max66 提出的形式。以下代码及其输出捕获了这三种形式的实际操作
#include <iostream>
#include <map>
using namespace std;
struct FooStruct
{
FooStruct()
{
cout << "FooStruct Default Constructor" << endl;
}
FooStruct(const FooStruct& other)
{
this->a = other.a;
this->b = other.b;
cout << "FooStruct Copy Constructor" << endl;
}
FooStruct(int a, int b)
{
this->a = a;
this->b = b;
cout << "FooStruct Parametrized Constructor" << endl;
}
int a;
int b;
};
输出:
foo.emplace<int, FooStruct>(0, {1, 2})
FooStruct Parametrized Constructor
FooStruct Copy Constructor
fooMap.emplace(make_pair<int, FooStruct>(1, { 2, 3 }))
FooStruct Parametrized Constructor
FooStruct Copy Constructor
FooStruct Copy Constructor
fooMap.emplace(std::piecewise_construct, std::forward_as_tuple(2), std::forward_as_tuple(2, 4))
FooStruct Parametrized Constructor
=============
原件(错误)
我有点懒惰,在发布问题之前没有尝试深入挖掘。我现在看到所有这三种形式(第三种形式来自@max66 的评论)都是等价的,因为它们都避免创建FooStruct
.
#include <iostream>
#include <map>
using namespace std;
struct FooStruct
{
FooStruct() { cout << "FooStruct Default Constructor" << endl; }
FooStruct(int a, int b) { this->a = a; this->b = b; cout << "FooStruct Parametrized Constructor" << endl; }
int a;
int b;
};
int main()
{
map<int, FooStruct> fooMap;
fooMap.emplace<int, FooStruct>(0, {1, 2});
fooMap.emplace(make_pair<int, FooStruct>(1, { 2, 3 }));
fooMap.emplace(std::piecewise_construct, std::forward_as_tuple(2), std::forward_as_tuple(2, 4));
return 0;
}
上述代码(使用 Visual C++ 2015 构建)产生以下输出:
FooStruct Parametrized Constructor
FooStruct Parametrized Constructor
FooStruct Parametrized Constructor
PS:我确实验证了上述输出中的每一行都对应于上面的单个 emplace 调用