I am new to c++11 and wrote the following code to understand how std::move
works:
#include <queue>
#include <stdio.h>
class X {
public:
X(int x) : x_(x) {}
~X() {
printf("X(%d) has be released.\n", x_);
}
X(X&&) = default;
X& operator = (X&&) = default;
X(const X&) = delete;
X& operator = (const X&) = delete;
private:
int x_;
};
int main() {
std::queue<X> xqueue;
for (int x = 0; x < 5; ++x) {
xqueue.push(std::move(X(x)));
}
return 0;
}
However, it generates the following output, which indicates that the destructor of each X(n)
has been called twice:
X(0) has be released.
X(1) has be released.
X(2) has be released.
X(3) has be released.
X(4) has be released.
X(0) has be released.
X(1) has be released.
X(2) has be released.
X(3) has be released.
X(4) has be released.
I can imagine the second round of the output happens right at the end of main()
function, and the first round probably happens in the loop when those intermediate X
s ran out of scope.
But, I thought the ownership of such intermediate X
s will be perfectly transferred into the queue and their destructors should not be called during their ownership transfer.
So my questions are:
- When I saw an instance being deallocated twice, does that mean it performs copy instead of move?
- If the above answer is yes, then how can I really avoid copying?
Thank you,