c++ - 我们应该在 C++17 及更高版本中使用临时对象的生命周期延长吗?

标签 c++ c++17

因为在 C++17 中,可以保证表达式创建的临时存储在分配给以下变量的变量中:

#include <iostream>

struct Test
{
    Test()                  { std::cout << "Test()"                 << std::endl;   }
    Test(const Test &rhs)   { std::cout << "Test(const Test &rhs)"  << std::endl;   }
    Test(Test &&rhs)        { std::cout << "Test(Test &&rhs)"       << std::endl;   }

    Test &operator=(Test &&rhs)         { std::cout << "Test &operator=(Test &&rhs)"        << std::endl; return *this; }
    Test &operator=(const Test &rhs)    { std::cout << "Test &operator=(const Test &rhs)"   << std::endl; return *this; }

    ~Test() { std::cout << "~Test()" << std::endl; }
};

Test fun()
{
    return Test{};
}

int main(int argc, char** argv)
{
    auto t = fun();

    return 0;
}

输出:

Test()
~Test()

删除赋值运算符以及复制和移动构造函数会产生相同的结果。

我们是否仍需要延长临时变量('const auto &t = fun()')的生命周期以进行任何类型的优化?

编辑:

Test &operator=(const Test &&rhs)   { std::cout << "Test &operator=(const Test &rhs)"   << std::endl; return *this; }

现在是:

Test &operator=(const Test &rhs)   { std::cout << "Test &operator=(const Test &rhs)"   << std::endl; return *this; }

编辑: 问题已澄清。

编辑: 删除了“语言律师”标签。这是一个真正的问题,影响了我的大部分代码库。出于性能原因,人们通常使用临时对象的生命周期延长。但是写'const auto &p = ...'比只写'auto p = ...'要长,这样更干净,也更能表达程序员的愿望。

最佳答案

是的,我仍然希望它能工作:

auto const& t = fun();

要实现这一点,需要延长临时 fun() 返回的生命周期以匹配 t 的生命周期。否则,Test 临时变量将在表达式末尾被销毁,我将立即拥有一个悬空引用。

如果“随便”给你一个左值,你需要某种方式来表达“给我随便”,避免工作。我不想执行 auto t = fun();,其中 fun() 返回 T const&,这是一个不必要的拷贝。 auto const&(或 auto&&)在这种情况下避免了复制,并且生命周期延长也适用于 prvalue 情况。

关于c++ - 我们应该在 C++17 及更高版本中使用临时对象的生命周期延长吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61870560/

相关文章:

c++ - 非模板类型参数

c++ - C++ 中的调度表

基于外部文件的 C++ 数组

c++ - 如何防止编译器忽略我未显式实例化的类型?

c++ - 如何获取参数包中元素的索引

c++ - 是否可以防止此代码出现 "copy and paste similar template special case"?

c++ - 动态可转换类型特征

c++ - 具有先前模板参数类型的自动返回类型参数的函数类型的模板参数

c++ - 计算独特项目的更好方法

c++ - Directory_iterator 跳过无法访问的文件夹 Windows