Memory allocation for function return value in a loop in C ++ 11: how is it optimized?

I tuned in for some premature optimization and wondered:

If one has a for loop, and inside this loop there is a function call that returns a container, say, a vector whose value is called as rvalue into a variable in the loop using move semantics, for example:

std::vector<any_type> function(int i)
{
  std::vector<any_type> output(3);
  output[0] = i;
  output[1] = i*2;
  output[2] = i-3;
  return(output);
}

int main()
{
  for (int i = 0; i < 10; ++i)
  {
    // stuff
    auto value = function(i);
    // do stuff with value ...
    // ... but in such a way that it can be discarded in the next iteration
  }
}

How do compilers handle this memory when relocation semantics are applied (and that function will not be inlined)? I would suggest that the most efficient task is to allocate a single memory for all values, both inside the function and outside in the for-loop, which will be overwritten at each iteration.

, , , , . , , , , . , , , - :

void function(int i, std::vector<any_type> &output)
{
  // fill output
}

int main()
{
  std::vector<any_type> dummy; // allocate memory only once
  for (int i = 0; i < 10; ++i)
  {
    // stuff
    function(i, dummy);
    // do stuff with dummy
  }
}

, GCC, , , , Intel.

+3
2

, - , for-loop, .

, . ( , .) , Chandler Carruth.

, : function() . , clear(), , clear() function().

, ++ 11.

, . , , , . ++, . , , , , IO. , . , std::string.

+2

RVO. , , ( , ).

- loo. , , std:: array, , -, .

+5

All Articles