且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过取消引用NULL指针来分配引用

更新时间:2022-05-07 00:15:55

取消引用空指针未定义行为

未定义行为意味着任何事情都可能发生,因此无法定义行为。

An Undefined Behavior means anything can happen, So it is not possible to define a behavior for this.

不确定的是,我将第n次添加这个C ++标准报价,但似乎需要。

Admittedly, I am going to add this C++ standard quote for the nth time, but seems it needs to be.

关于未定义的行为,

C ++标准版1.3.24说明:

C++ Standard section 1.3.24 states:


允许未定义的行为范围该情况完全具有不可预测的结果,在以文件化的环境特征(有或没有诊断消息的发布)的方式执行翻译或程序期间行为,终止翻译或执行(发出诊断消息)。

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

注意

此外,请注意: br>
使用返回的引用或指向函数内的局部变量的指针也是未定义的行为。你应该使用new分配指针在freestore(堆),然后返回一个引用/指针。

NOTE:
Also, just to bring it to your notice:
Using a returned reference or pointer to a local variable inside a function is also an Undefined Behavior. You should be allocating the pointer on freestore(heap) using new and then returning a reference/pointer to it.

编辑:

正如@James McNellis在评论中恰当地指出,

如果未使用返回的指针或引用,则行为明确