简体   繁体   English

在Xcode 6.3下,NULL C ++参考地址的值为非零

[英]Under Xcode 6.3, NULL C++ reference address evaluates as non-zero

Similar to this question: XCode 6.3 Warning : Comparison of address of 'myObject' not equal to null pointer is always true 与此问题类似: XCode 6.3警告:“ myObject”的地址不等于空指针的比较始终为true

with C++, I found that previously working code for evaluating null pointers stopped working: 使用C ++,我发现先前用于评估空指针的代码停止了工作:

struct AStruct
{
    int x, y;
    char *name;
};

AStruct& GetStruct()
{
   return *(AStruct*)0;
}

int main(int argc, const char * argv[]) {

    AStruct& mys = GetStruct();

    if ( ! &mys) {
        printf("null pointer \n");
    }
    else
    {
        printf("NOT a null pointer\n");
    }

    return 0
}

This always prints out NOT a null pointer 这总是打印出NOT a null pointer

I've tried other ways of pointer-to-reference checking: 我尝试了指针引用检查的其他方式:

if ( &mys == NULL)

if ( &mys == nullptr )

None of these worked. 这些都不起作用。

Then I noticed the warning: 然后我注意到了警告:

Reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to false

But there are no suggested fixes. 但是没有建议的修复程序。

What is the canonical way of checking null pointers these days? 这些天来检查空指针的规范方法是什么?

You are not checking against a pointer, you are checking against a reference. 您不是在检查指针,而是在检查引用。

References are not supposed to be nullptr since they must refer to an existing value. 引用不应为nullptr因为它们必须引用现有值。 Indeed what you are doing *(AStruct*)0 is not well defined since a reference shouldn't be able to generate undefined behaviour through "dereferencing it" but in this way you could trigger the problem. 确实,您正在做的*(AStruct*)0定义不正确,因为引用不应通过“取消引用”来生成未定义的行为,但是您可以通过这种方式触发问题。

If client code has a AStruct& then it can be sure that the reference points to something, you are breaking this condition. 如果客户端代码具有AStruct&则可以确保引用指向某物,那么您正在打破这种情况。

If you need to work with references that can be null use a pointer, eg 如果您需要使用可以为null的引用,请使用指针,例如

AStruct* GetStruct()
{
  return nullptr;
}

if (!GetStruct())
{
  ...

The fact that the code worked in a previous version of Xcode is a symptom of the fact that this is not well-defined code. 该代码可在Xcode的早期版本中使用的事实是以下事实的症状:该代码定义不明确。

You don't have a pointer there; 你那里没有指针。 mys is a reference. mys是参考。 Then when you check the value of &mys , you are checking the address of the reference. 然后,当您检查&mys的值时,您正在检查引用的地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM