匿名对象

内容简介

匿名对象是没有名字的临时对象。它通常在表达式中创建,表达式结束后销毁。

用法

class Person {
public:
    Person()
    {
        std::cout << "constructor\n";
    }
 
    ~Person()
    {
        std::cout << "destructor\n";
    }
};
 
Person();  // 创建一个匿名对象,随后销毁

常见场景:

std::string("hello");
std::vector<int>{1, 2, 3};

临时对象和函数调用

void print(const std::string& text)
{
    std::cout << text << '\n';
}
 
print(std::string("hello"));

临时对象可以绑定到 const 引用,生命周期会延长到函数调用结束。

最佳代码实践

  • 临时对象适合表达一次性值。
  • 构造复杂对象时,优先给它命名,提高可读性。
  • 不要返回局部对象的引用或指针。

错误用法

const std::string& bad()
{
    return std::string("hello");  // 错误:返回临时对象引用
}

函数返回后临时对象已经销毁,引用悬空。

注意事项

  • 匿名对象和 RVO、移动语义、临时对象生命周期强相关。
  • 初学阶段先理解“什么时候创建,什么时候销毁”。

学习路径