我有一个
vector
容器,类型名称是std::pair
,但是我发现添加元素时有很多构造/解构操作。
这是一个演示代码:
#include <iostream>
#include <vector>
using namespace std;
struct A {
explicit A(int a) : a_(a) {
printf("%d created at %p\n", a_, (void *)this);
}
A(const A &other) : a_(other.a_) { printf("%d copied\n", a_); }
A(A &&other) : a_(other.a_) {
printf("%d moved into %p\n", a_, (void *)this);
}
A &operator=(const A &other) {
printf("%d copy assigned\n", a_);
a_ = other.a_;
return *this;
}
A &operator=(A &&other) {
printf("%d move assigned to %p\n", a_, (void *)this);
a_ = other.a_;
return *this;
}
~A() { printf("%d %p dead\n", a_, (void *)this); }
int a_;
void show() const { printf("%d\n", a_); }
};
int main() {
std::vector<std::pair<A, A>> v;
v.emplace_back(std::make_pair(A(1), A(2)));
while(1);
}
g++ a.cpp -O2
./a.out
2 created at 0x7fffb413ca84
1 created at 0x7fffb413ca80
1 moved into 0x7fffb413ca88
2 moved into 0x7fffb413ca8c
1 moved into 0x1cf72c0
2 moved into 0x1cf72c4
2 0x7fffb413ca8c dead
1 0x7fffb413ca88 dead
1 0x7fffb413ca80 dead
2 0x7fffb413ca84 dead
如输出所示:
创建了四个临时变量,如何减少它?
为什么不直接写
v.emplace_back(1, 2);
而不是你目前拥有的:
v.emplace_back(std::make_pair(A(1), A(2)));
?
运行这段代码,我只得到:
1 created at 0x586bf7ac12b0
2 created at 0x586bf7ac12b4