2)凡含有表达式执行结果的临时性对象,应该存留到object的初始化操作完成为止。
示例代码如下:
class A
{
public:
A(int i = 0): m_i(i)
{
cout << "A(): " << m_i << endl;
}
~A()
{
cout << "~A(): " << m_i << endl;
}
A operator+(const A& rhs)
{
cout << "A operator+(const A& rhs)" << endl;
return A(m_i + rhs.m_i);
}
A& operator=(const A& rhs)
{
cout << "A& operator=(const A& rhs)" << endl;
m_i += rhs.m_i;
return *this;
}
int m_i;
};
int main()
{
A a1(1), a2(2);
A a3;
a3 = a1 + a2; //a1 + a2产生的临时变量在a3的赋值操作完成后,才释放
return 0;
}
新闻热点
疑难解答
图片精选