这== NULL //这怎么可能? [英] this == null // How can it be possible?
问题描述
最近我遇到了我的应用程序的一些奇怪的行为。它已经开发主要在C#但CLI / C ++也用于实现更好的性能。我是在时间跨度比较得到一个System.NullReferenceException在一个非常简单的方法:
Recently I came across some strange behaviour of my application. It has been developed mainly in C# but CLI/C++ was also used to achieve better performance. I was getting a System.NullReferenceException in a very simple method at the TimeSpan comparison:
TimeSpan _timestamp;
void UpdateFrame(TimeSpan timestamp)
{
if(TimeSpan::Equals(_timestamp, timestamp) == false)
很明显,在这个前pression使用的唯一参照的是隐含的这个(this._timestamp)。我添加了一个断言语句,它原来,这实际上是空。经过简短的调查,我设法ppared短节目presenting这种现象$ P $。这是C ++ / CLI。
It was obvious that the only reference used in this expression was implicit this (this._timestamp). I added an assert statement and it turned out that this is actually null. After short investigation I managed to prepared short program presenting this phenomenon. It is 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;
}
有谁知道这怎么可能?它是在编译器中的错误?
Does anybody know how can it be possible? Is it a bug in the compiler?
推荐答案
在C ++(和presumably在C ++ / CLI)没有什么$ P $从试图调用一个空指针的方法pventing你。在大多数实现中,一个虚方法调用会崩溃的调用点,因为运行时将无法读取虚拟方法表。但是,的非虚的方法调用只是一些参数,其中一个是这
指针函数调用。如果它是零,那么这就是被传递给函数。
In C++ (and presumably in C++/CLI) there's nothing preventing you from trying to call methods on a NULL pointer. In most implementations, a virtual method call will crash at the point of the call because the runtime won't be able to read the virtual method table. However, a non-virtual method call is just a function call with some parameters, one of which is the this
pointer. If it's null, then that is what is passed to the function.
我相信呼吁一个 NULL
(或 nullptr
)的指针是正式未定义的任何成员函数的结果行为。
I believe the result of calling any member function on a NULL
(or nullptr
) pointer is officially "undefined behaviour".
这篇关于这== NULL //这怎么可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!