I am trying to better understand construction, moving and copying objects.
To test when each operation is happening I have created the following struct:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
#include <vector>
struct Object
{
Object() { std::cout << "Constructed" << std::endl; }
Object(const Object& object) { std::cout << "Copied" << std::endl; }
Object(Object&&) noexcept { std::cout << "Moved" << std::endl; }
~Object() { std::cout << "Destroyed" << std::endl; }
};
|
1. I was told the following would prevent an unnecessary copy:
1 2 3 4 5 6 7 8
|
int main()
{
std::vector<Object> objects;
Object obj;
// Do stuff with obj..
objects.emplace_back(obj);
}
|
However according to my tests to standard out, this is definitely making a copy, the output is:
Constructed
Copied
Destroyed
Destroyed
|
They said it was the same as writing
objects.push_back(std::move(obj))
, either I'm missing something or this is incorrect, the only way to replicate that with emplace_back for me was to write
objects.emplace_back(std::move(obj))
which will now output "Moved" instead.
2. Even if I were to use
std::move(obj)
and have the object moved, what benefit does this provide? I still seem to have two instances as I can access the original obj, and I get two calls to the destructor.
I think I've managed to just really confuse myself :)