c++操作符重载中返回引用和不返回引用的区别是什么?
what is the differences between returning reference or not in operator overloading C++
我试图弄清楚&在返回类型上。我的意思是,考虑下面的代码,如果我删除&操作符重载函数
class Container
{
public:
int numElems;
int *data;
Container(int n):numElems(n){data=new int [numElems];}
Container & operator=(const Container &rhs)
{
if(this!=&rhs)
{
if(data!=NULL)
delete [] data;
numElems=rhs.numElems;
data=new int [numElems];
for (int i=0;i<numElems;i++)
{
data[i]=rhs.data[i];
}
return *this;
}
}
};
删除后编译,编译后没有任何错误。实际上,对于一个示例main:
,它在两种情况下给出相同的结果:int main()
{
Container a(3);
Container b(5);
Container c(1);
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
a=b=c;
cout<<a.numElems<<endl;
cout<<b.numElems<<endl;
cout<<c.numElems<<endl;
return 0;
}
那么,有没有人可以帮助我关于&在左边吗?提前感谢。
class foo {
public:
int val;
foo() { }
foo(int val) : val(val) { }
foo& operator=(const foo &rhs) {
val = rhs.val;
return *this;
}
foo& operator++() {
val++;
return *this;
}
};
void main() {
foo f1(10), f2;
(f2 = f1)++;
std::cout << f1.val << " " << f2.val << std::endl;
}
输出: 10 11
删除引用时的输出:
10 10
返回一个引用比返回一个大对象的值要快得多。这是因为在底层,引用只是一个内存地址而如果按值返回它就需要深度复制
如果不返回引用,则隐式地进行了不必要的额外复制。
相关文章:
- 寿命延长从函数返回引用
- 了解C++如何返回引用并绑定到引用
- 返回引用实例和非引用实例(return mystr & vs mystr)之间的区别是什么?
- 从类返回引用向量
- 使用unique_ptr并返回引用,或者我应该使用shared_ptr并在需要时制作副本
- 混淆C++从函数返回引用
- 两个相同的重载运算符[]一个返回引用
- 为什么向量的.at()成员函数返回引用而不是迭代器
- C++使用和返回引用
- 返回 T 引用的 Const 函子禁止赋值
- 返回引用是否也会延长其生存期?
- 如何返回引用,然后递增迭代器
- 如果使用返回引用的函数初始化"auto"var,为什么它不声明引用类型?
- 我是否需要将 ref 与 make_pair 一起使用才能返回引用?
- 在 vector::at 返回引用后进行更改
- 为什么PyImport_ImportModule返回引用计数为 3 而不是 1 的 PyObject*
- 超出返回引用的单一实例生存期
- Boost.Python 返回引用现有 c++ 对象的 python 对象
- C++ 运算符 += 重载返回引用
- 如何声明接受转发引用并返回引用或副本的函数模板