Temporaries - C++11, 17 of n

本文详细阐述了C++中运算符重载的实现方式,特别是涉及临时对象时的行为,包括如何在函数调用中利用临时对象进行高效的数据传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1) 
struct S {
S();
S(int);
friend S operator+(const S&, const S&);
~S();
};
const S& cr = S(16)+S(23);
The temporary result of "S(16) + S(23)" bound to "cr" persists until the end life of "cr".

2) Example
class X {
public:
    X(int);
    X(const X&);
    X& operator=(const X&);
    ~X();
};

class Y {
public:
    Y(int);
    Y(Y&&);
    ~Y();
};

X f(X);
Y g(Y);

void h() {
    X a(1);
    X b = f(X(2));
    Y c = g(Y(3));
    a = f(a);

}

An implementation might use a temporary in which to construct X(2) before passing it to f() using X’s copy constructor; alternatively, X(2) might be constructed in the space used to hold the argument.
Likewise, an implementation might use a temporary in which to construct Y(3) before passing it to g() using Y’s move constructor; alternatively, Y(3) might be constructed in the space used to hold the argument.
Also, a temporary might be used to hold the result of f(X(2)) before copying it to b using X’s copy constructor; alternatively, f()’s result might be constructed in b.
Likewise, a temporary might be used to hold the result of g(Y(3)) before moving it to c using Y’s move constructor; alternatively, g()’s result might be constructed in c.
On the other hand, the expression a=f(a) requires a temporary for the result of f(a), which is then assigned to a.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值