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

我确实看到了

> Difference between pointer variable and reference variable in C++讨论了它们之间的差异.

编辑-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;
}

编辑:因为似乎有一些关于引用是对象的别名还是绑定到内存位置的混淆,这里是标准的段落(草案3225,部分[basic.life]),它明确指出参考绑定存储并且可以比创建引用时存在的对象寿命更长:

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引用被认为比指针更安全? - 乐贴网