Pao*_*oni 3 c++ reference c++11
看这段小代码:
std::deque<BIG> bigs {};
// add some BIGs in the deque
BIG& last_BIG { bigs.front() };
f(last_BIG);
bigs.pop_front();
g();
Run Code Online (Sandbox Code Playgroud)
调用后pop_front引用last_BIG无效,这是否足以使程序格式错误?换句话说,我是否必须放入last_BIG更小的范围?
当然,弹出后使用是未定义的。 last_BIG
不,无效引用或无效指针本身并不会使您的程序无效。在它失效后使用它肯定是未定义的,但创建它本身并不是问题。
这与创建悬挂指针类似,只不过指针提供了更多使它们失效的方法:
int *a = new int;
delete a;
Run Code Online (Sandbox Code Playgroud)
此时a是一个无效的指针,就像pop_front代码中的afterlast_BIG是一个无效的引用一样。只要您不取消引用无效的指针或访问无效的引用,就可以了。