Why is a c++ reference considered safer than a pointer?

It's considered safer because a lot of people have "heard" that it's safer and then told others, who now have also "heard" that it's safer.

Not a single person who understands references will tell you that they're any safer than pointers, they have the same flaws and potential to become invalid.

e.g.

#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;
}

EDIT: Since there seems to be some confusion about whether a reference is an alias for an object or bound to a memory location, here's the paragraph from the standard (draft 3225, section [basic.life]) which clearly states that a reference binds to storage and can outlive the object which existed when the reference was created:

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).

如果类的生存期结束后并且它所占用的存储位置重新被使用或者释放,新创建的类恰好建立在原先类的存储空间上,指针指向原先类,引用引向原来类。

或者,原来类的名字可以自动引用新类或者一旦新类的生存周期开始,原来的类名可以操作新的类,只有下列情况都满足才可以:

1. 新的类的存储空间是原来类占有的

2.新类和原来先是相同的类型

3.原来类不是const类型,如果是class的类型,它不包含const类型的或者引用类型的非静态的数据成员

4.他们不是基类的子类

原谅我吧,太拗口了。

你可能感兴趣的:(reference)