Avoid copying when clicking an item in std :: queue

I am new to C ++ 11 and would like to have std :: queue save class instances Xand try to avoid unnecessary copies in push . In C ++ 11, I found that it push()has a reference version of rvalue:

void push (value_type&& val);

Thus, the following implementation eliminates unnecessary copy X

std::queue<X> my_queue;

for (...) { // some for loop
  X x;
  ... // some initialization of x
  my_queue.push(std::move(x));
}

compared to the next naive implementation?

std::queue<X> my_queue;

for (...) { // some for loop
  X x;
  ... // some initialization of x
  my_queue.push(x);
}
+3
source share
2 answers

If and only if X supports the semantics of movement, the first of them is beautiful.

X may look like:

struct X {
    int value;
    X() {
        static int n;
        value = ++n;
    }

    X(X&&) = default;
    X& operator = (X&&) = default;

    X(const X&) = delete;
    X& operator = (const X&) = delete;
};

Note: a copy of X is not permitted here.

+1
source

The best way to answer such a question is to create a probe object.

#include <iostream>
struct probe {
    probe() { std::cout << "probe()" << ((void*)this) << std::endl; }
    probe(const probe&) { std::cout << "probe(c&)" << ((void*)this) << std::endl; }
    probe(probe&&) { std::cout << "probe(&&)" << ((void*)this) << std::endl; }
    ~probe() { std::cout << "~probe()" << ((void*)this) << std::endl; }
};

and use it instead of X in the test.

.

, -, std::move, , rvalue.

+2

All Articles