源自 stackoverflow 论坛,很有意义
第一个问题,引用传递和按值传递的场合
There are four main cases where you should use pass-by-reference over pass-by-value:
- If you are calling a function that needs to modify its arguments, use pass-by-reference or pass-by-pointer. Otherwise, you’ll get a copy of the argument.
- If you're calling a function that needs to take a large object as a parameter, pass it by const reference to avoid making an unnecessary copy of that object and taking a large efficiency hit.
- If you're writing a copy or move constructor which by definition must take a reference, use pass by reference.
- If you're writing a function that wants to operate on a polymorphic class, use pass by reference or pass by pointer to avoid slicing.
来源:Where should I prefer pass-by-reference or pass-by-value?
第二个问题,地址运算符(&)和引用运算符(&)的区别 代码解释,int v = 5; cout << v << endl; // prints 5 cout << &v << endl; // prints address of v int* p; p = &v; // stores address of v into p (p is a pointer to int) int& r = v; cout << r << endl; // prints 5 r = 6; cout << r << endl; // prints 6 cout << v << endl; // prints 6 too because r is a reference to v
问题中更有意思的是对 *this 的解释,
Firstly, this
is a pointer. The *
dereferences the pointer, meaning return *this;
returns the object, not a pointer to it.
Secondly, Test&
is returning a reference to a Test
instance. In your case, it is a reference to the object. To make it return a pointer, it should be Test*
.
来源:Address-of operator (&) vs reference operator(&)
附 C++ 各个阶段学习的书籍推荐,来源论坛大牛的回答
C++ 并发编程实战感觉包含挺多工作上需要的知识点,比如,线程库、原子库、C++ 内存模型、锁和互斥锁,以及设计和调试多线程应用程序的问题,可以看看
标签:use,reference,object,C++,引用,pass,pointer,指针 From: https://www.cnblogs.com/strive-sun/p/16809942.html