Should this code print empty (Clang & GCC), or not empty (Visual C++)?
Should that change if I remove reserve()? What about using emplace() instead of insert()?
#include <stdio.h>
#include <memory>
#include <vector>
int main()
{
std::vector<std::shared_ptr<int> > v;
v.reserve(10); // Should this affect the output?
v.push_back(std::make_shared<int>(0));
v.insert(v.begin(), std::move(v.front())); // Does 'emplace' vs. 'insert' matter?
printf("Element 0 is: %s\n", v[0] ? "not empty" : "empty");
return 0;
}
Logically not empty makes more sense to me for insert, because the caller of insert is requesting movement from a particular object, and we need to ensure that's what we're moving from. Moreover, it seems silly for reserve() to affect which element ends up where.
However, that would imply both libstdc++ (GCC) and libc++ (Clang) are buggy, which doesn't seem likely.
Perhaps more interestingly, I'm less certain about emplace. I'm inclined to think using emplace should logically output empty, because the caller is requesting construction to occur at in the object's correct place ("emplace"), which requires movement to occur before construction.
What is the correct behavior of moving from a container into itself? Does it depend on the specifics of which of insert/emplace/reserve are called? Is it implementation-defined?
For what it's worth, cppreference.com says the following for emplace:
If the required location has been occupied by an existing element, the inserted element is constructed at another location at first, and then move assigned into the required location.
but that goes against what both GCC and Clang do for emplace, as well as against my expectation above (which differs from my expectation for insert).