最近,我遇到了我的应用程序的一些奇怪行为。它主要是用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/