指针和引用参数之间的区别?

2023-02-13C/C++开发问题
3

本文介绍了指针和引用参数之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这些都一样吗:

int foo(bar* p) {返回 p->someInt();}

int foo(bar& r) {返回 r.someInt();}

忽略空指针的潜力.无论 someInt() 是虚拟的还是传递一个 barbar 的子类,这两个函数在功能上是否相同?>

这个切片有什么作用:

bar&ref = *ptr_to_bar;

解决方案

C++ 引用在标准中有意未指定使用指针实现.引用更像是变量的同义词",而不是指向它的指针.当有可能意识到指针在某些情况下是多余的时,这种语义为编译器打开了一些可能的优化.

还有一些区别:

  • 您不能将 NULL 分配给引用.这是一个关键的区别,你更喜欢一个的主要原因其他.
  • 当你获取一个地址时指针,你得到的地址指针变量.当你拿参考地址,您将获得变量的地址是提及.
  • 您无法重新分配参考.初始化后,它在整个生命周期中都指向同一个对象.

Are these the same:

int foo(bar* p) {
  return p->someInt();
}

and

int foo(bar& r) {
  return r.someInt();
}

Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?

Does this slice anything:

bar& ref = *ptr_to_bar;

解决方案

C++ references are intentionally not specified in the standard to be implemented using pointers. A reference is more like a "synonym" to a variable than a pointer to it. This semantics opens some possible optimizations for the compiler when it's possible to realize that a pointer would be an overkill in some situations.

A few more differences:

  • You can't assign NULL to a reference. This is a crucial difference and the main reason you'd prefer one over the other.
  • When you take the address of a pointer, you get the address of the pointer variable. When you take the address of a reference, you get the address of the variable being referred to.
  • You can't reassign a reference. Once it is initialized it points to the same object for its entire life.

这篇关于指针和引用参数之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6