C++ 值,指针,引用的讨论

源自 stackoverflow 论坛,很有意义

第一个问题,引用传递和按值传递的场合

There are four main cases where you should use pass-by-reference over pass-by-value:

  1. 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.
  2. 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.
  3. If you're writing a copy or move constructor which by definition must take a reference, use pass by reference.
  4. 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;
}

回答:

如果你需要修改指针而不是指针指向的对象,你可能希望通过引用传递指针。(如果没有引用,你只会更改指针的本地副本)

这类似于为什么使用双指针;使用对指针的引用比使用指针稍微安全一些。

来源:Reason to Pass a Pointer by Reference in C++?


 

附 C++ 各个阶段学习的书籍推荐,来源论坛大牛的回答

C++ 并发编程实战感觉包含挺多工作上需要的知识点,比如,线程库、原子库、C++ 内存模型、锁和互斥锁,以及设计和调试多线程应用程序的问题,可以看看

原文链接: https://www.cnblogs.com/strive-sun/p/16809942.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ 值,指针,引用的讨论

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404424

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月25日 下午4:34
下一篇 2023年4月25日 下午4:34

相关推荐