存储的临时对象在哪里

Where is the temporary object stored?

本文关键字:在哪里 临时对象 存储      更新时间:2023-10-16

我想知道调用const reference的函数时,临时对象在哪里存储。

在下面的方案中,在 foo 函数中,我们创建一个临时 std :: string 对象,然后将其作为参数传递给 print_name 能。获取const引用。它是否存储在堆上的某个地方,而不是在 print_name 函数范围内被销毁。

谢谢

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

它存储在堆栈上,而不是堆中。但是请注意,std::string可能利用了堆。