因为在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; }编辑:问题已澄清。
编辑:删除了“language-lawyer”标签。这是一个真正的问题,影响了我的代码库。出于性能原因,人们通常使用时态的生命周期扩展。但是写入'const auto &p = ...‘比仅仅写'auto p= ...‘更长,更简洁,更能表达程序员的愿望。
发布于 2020-05-18 21:32:44
是的,我仍然希望它能正常工作:
auto const& t = fun();要做到这一点,需要延长临时fun()返回的生命周期,以与t的生命周期相匹配。否则,Test临时值将在表达式的末尾被销毁,我会立即得到一个悬空的引用。
你需要一些方式来说“给我任何东西”,如果“任何东西”给你一个左值,就可以避免工作。我不想做fun()返回T const&的auto t = fun();,这是一个不必要的拷贝。在这种情况下,auto const& (或auto&&)避免了复制,并且带有生存期扩展也适用于prvalue情况。
https://stackoverflow.com/questions/61870560
复制相似问题