gpt4 book ai didi

c++ - 为什么 C++ 引用被认为比指针更安全?

转载 作者:可可西里 更新时间:2023-11-01 16:25:35 25 4
gpt4 key购买 nike

当 C++ 编译器为引用和指针生成非常相似的汇编代码时,为什么与指针相比更喜欢使用引用(并且被认为更安全)?

我看到了

EDIT-1:

我正在查看 g++ 为这个小程序生成的汇编代码:

int main(int argc, char* argv[])
{
int a;
int &ra = a;
int *pa = &a;
}

最佳答案

它被认为更安全,因为很多人“听说”它更安全,然后告诉其他人,而这些人现在也“听说”它更安全。

没有一个了解引用的人会告诉您它们比指针更安全,它们具有相同的缺陷并且有可能变得无效。

例如

#include <vector>

int main(void)
{
std::vector<int> v;
v.resize(1);

int& r = v[0];
r = 5; // ok, reference is valid

v.resize(1000);
r = 6; // BOOM!;

return 0;
}

编辑:由于似乎对引用是对象的别名还是绑定(bind)到内存位置存在一些混淆,这里是标准中的段落(草案 3225,部分 [basic.life]),它清楚地表明引用绑定(bind)到存储,并且可以比创建引用时存在的对象长寿:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

  • the storage for the new object exactly overlays the storage location which the original object occupied, and
  • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
  • the original object was a most derived object of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

关于c++ - 为什么 C++ 引用被认为比指针更安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com