c++vectorstd-pair

How to avoid tempory variable create and dead when emplace_back a pair object?


I have a vector container, typename is std::pair, but i found there are many construct/deconstruct operation when add element.

Here is a demo code:

#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

as the output shows:

there are four temp variable was created, how to reduce it?


Solution

  • Why not just write v.emplace_back(1, 2); instead of what you currently have: v.emplace_back(std::make_pair(A(1), A(2))); ?

    Running this modified code, I get only:

    1 created at 0x586bf7ac12b0
    2 created at 0x586bf7ac12b4