.net - this == null//怎么可能?

标签 .net visual-c++ c++-cli

最近,我遇到了我的应用程序的一些奇怪行为。它主要是用C#开发的,但也使用CLI / C++来获得更好的性能。我在TimeSpan比较中以非常简单的方法获取了System.NullReferenceException:

TimeSpan _timestamp;
void UpdateFrame(TimeSpan timestamp)
{
    if(TimeSpan::Equals(_timestamp, timestamp) == false) 

显然,此表达式中使用的唯一引用是隐式this(this._timestamp)。我添加了一个assert语句,结果证明这实际上是空的。经过简短的调查,我设法准备了介绍此现象的简短程序。它是C++ / CLI。
using namespace System;
using namespace System::Reflection;

public class Unmanaged
{
public:
    int value;
};

public ref class Managed
{
public:
    int value;

    Unmanaged* GetUnmanaged()
    {
        SampleMethod();
        return new Unmanaged();
    }

    void SampleMethod()
    {
        System::Diagnostics::Debug::Assert(this != nullptr);
        this->value = 0;
    }
};

public ref class ManagedAccessor
{
public:
    property Managed^ m;
};

int main(array<System::String ^> ^args)
{
    ManagedAccessor^ ma = gcnew ManagedAccessor();
    // Confirm that ma->m == null
    System::Diagnostics::Debug::Assert(ma->m == nullptr);
    // Invoke method on the null reference
    delete ma->m->GetUnmanaged();
    return 0;
}

有人知道怎么可能吗?这是编译器中的错误吗?

最佳答案

在C++中(大概在C++ / CLI中),没有什么阻止您尝试在NULL指针上调用方法的。在大多数实现中,虚拟方法调用将在调用时崩溃,因为运行时将无法读取虚拟方法表。但是,非虚拟方法调用只是带有某些参数的函数调用,其中之一是this指针。如果为null,则传递给函数。

我相信在NULL(或nullptr)指针上调用任何成员函数的结果是正式的“未定义行为”。

关于.net - this == null//怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2679080/

相关文章:

C# 表达式返回 TSQL 包含关键字

c# - 带有嵌入式图像/css 的 ServiceStack Razor(自托管)

c++-cli - libcurl编译和链接器错误

c++-cli - 从 JSON 文件 c/cli 获取字符串

c# - 生成某些数据的防篡改签名?

c# - .NET 字符串和引用类型参数

string - 如何检查 CComBSTR 是否以特定前缀开头?

visual-c++ - Visual C++ PDB 文件的合理大小是多少?

c++ - 为什么我的程序在 windows 上读取文件比在 Ubuntu 上需要更长的时间

c# - 如何在 C++/cli 中声明委托(delegate)并在 C# 中使用它