C++ 值,指针,引用的讨论
源自 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(&)
第三个问题,通过引用传递指针的原因
考虑这样的代码,
template<typename T> void moronic_delete(T*& p) { delete p; p = nullptr; }
回答:
如果你需要修改指针而不是指针指向的对象,你可能希望通过引用传递指针。(如果没有引用,你只会更改指针的本地副本)
这类似于为什么使用双指针;使用对指针的引用比使用指针稍微安全一些。
附 C++ 各个阶段学习的书籍推荐,来源论坛大牛的回答
C++ 并发编程实战感觉包含挺多工作上需要的知识点,比如,线程库、原子库、C++ 内存模型、锁和互斥锁,以及设计和调试多线程应用程序的问题,可以看看