临时对象

C++临时对象与拷贝构造函数调用分析
博客展示了一段C++代码,定义了Bar类,包含构造函数、拷贝构造函数和析构函数等。函数foo返回Bar类临时对象,在main函数中使用该临时对象。代码在VC和GCC中运行,未调用拷贝构造函数,并给出了具体输出结果。
临时对象
 
#include <iostream>
#include <cstring>
 
using namespace std;
 
class Bar {
public:
    Bar(const char* _name) {
        cout << "ctor" << endl;
        strcpy(name, _name);
    }
    Bar(const Bar& other) {
        cout << "cp ctor" << endl;
        strcpy(name, other.name);
    }
    virtual ~Bar() {
        cout << "dtor" << endl;
    }
 
    const char* getName() const{
        return name;
    }
 
    void setName(const char* _name) {
        strcpy(name, _name);
    }
   
    char name[256];
};
 
Bar foo() {
    return Bar("bar");
}
 
int main() {
    Bar bar(foo());
    cout << foo().getName() << endl;
    return 0;
}
 
在VC和GCC中都没有调用过 copy constructor
 
输出
ctor
ctor
bar
dtor
dtor
在C++中,**临时对象(Temporary Object)**是指那些没有显式命名的、在表达式求值过程中自动创建并在使用后销毁的对象。它们通常由编译器隐式生成,生命周期短暂,仅存在于当前表达式的作用域内。 ### **临时对象的常见来源** 1. **函数返回的非引用类型对象** ```cpp std::string getName() { return "Alice"; } // 返回值是临时对象 std::string name = getName(); // 临时对象被拷贝或移动给name ``` 2. **类型转换(隐式或显式)** ```cpp int x = 10; double y = x + 5.5; // x被隐式转换为临时double对象 ``` 3. **构造对象但未命名(如直接初始化)** ```cpp std::vector<int> getVec() { return std::vector<int>{1, 2, 3}; } // 临时vector ``` 4. **算术或逻辑运算的中间结果** ```cpp int a = (x + y) * z; // (x + y) 产生临时int对象 ``` ### **临时对象的生命周期** - **默认情况**:临时对象的生命周期持续到**完整表达式结束**(即分号`;`)。 - **绑定到`const&`或`&&`时**:生命周期会**延长**至引用变量的作用域结束: ```cpp const std::string& tempRef = getName(); // 临时对象生命周期延长 std::string&& rvalRef = getName(); // 同样延长生命周期 ``` ### **优化:返回值优化(RVO/NRVO)** 现代编译器会优化临时对象的拷贝/移动操作: - **RVO (Return Value Optimization)**:直接构造返回值到目标位置,避免临时对象。 - **NRVO (Named Return Value Optimization)**:对命名局部变量做类似优化。 ```cpp std::string makeString() { std::string s = "Hello"; // NRVO可能直接构造到调用方 return s; } ``` ### **示例:Eigen中的临时对象** ```cpp Eigen::Vector3d vec = Eigen::Vector3d(1, 2, 3) + Eigen::Vector3d(4, 5, 6); // 两个临时Vector3d在加法后生成新临时对象,再拷贝/移动给vec ``` ### **关键点总结** - 临时对象是**右值(rvalue)**,可被移动(C++11起)。 - 避免不必要的临时对象可提升性能(如用`+=`替代`+`)。 - `const&`或`&&`可延长临时对象生命周期。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值