Здесь это демонстрационный код:
Код: Выделить всё
#include
#include
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 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
было создано четыре временные переменные, как их уменьшить?
Подробнее здесь: https://stackoverflow.com/questions/791 ... air-object
Мобильная версия