1

I was wondering where a temporary object is stored when calling a function that takes a const reference.

In the scenario below, in the foo function we create a temporary std::string object and pass it as an argument to print_name function. Which takes a const reference. Is it stored somewhere on a heap and than gets destroyed as soon as print_name function goes out of scope?

Thanks

void print_name(const std::string& name)
{
      std::cout << name << std::endl;
}

void foo()
{
    print_name( std::string("John") );
}
Gene
  • 661
  • 4
  • 10
  • 21
  • Didn't catch that they're constructing a `std::string` within the call, you are correct. At first glance I thought they just called the function with a literal. – Cory Kramer May 12 '15 at 13:33

1 Answers1

0

It's stored on the stack, not the heap. Note however that std::string probably makes use of the heap.

Steve
  • 1,760
  • 10
  • 18