Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 207

When does assigning the return value result in a copy?

$
0
0

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:

  1. firstMap and thirdMap could be copies of the return value of newUnorderedMap()
  2. All of the others would not result in copies, but a move/swap
  3. The ampersand in the auto declaration of sixthMap would essentially be ignored, and sixthMap would be identical to fifthMap 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


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>