There are six lines in int main
below where a variable is being created and initialized; in which (if any) of these scenarios does a copy get created for the assignment?
Additionally, in the case of sixthMap
, does/could anything weird happen, since we're using automatic deduction with an ampersand but the function it's calling also returns a reference?
std::unordered_map<std::string, std::vector<std::string>>createStdObject(){ std::unordered_map<std::string, std::vector> newUnorderedMap { {"A", {"first", "vector", "in", "map"}, {"B", {"second", "vector", "in", "map"} }; return newUnorderedMap;}std::unordered_map<std::string, std::vector<std::string>>&createStdObjectWithReference(){ std::unordered_map<std::string, std::vector> newUnorderedMap { {"A", {"first", "vector", "in", "map"}, {"B", {"second", "vector", "in", "map"} }; return newUnorderedMap;}int main(){ std::unordered_map<std::string, std::vector> firstMap = newUnorderedMap(); std::unordered_map<std::string, std::vector> secondMap = createStdObjectWithReference(); const auto thirdMap = newUnorderedMap(); const auto& fourthMap = newUnorderedMap(); const auto fifthMap = createStdObjectWithReference(); const auto& sixthMap = createStdObjectWithReference();}
What I would guess - based on my limited knowledge - is:
firstMap
andthirdMap
could be copies of the return value ofnewUnorderedMap()
- All of the others would not result in copies, but a move/swap
- The ampersand in the auto declaration of
sixthMap
would essentially be ignored, andsixthMap
would be identical tofifthMap
in terms of type and behaviour
On the other hand, it is obvious at compile time itself that none of the return values actually need to be copied, and as such I see no reason why they shouldn't all result in a move assignment