質問

Mistakenly I wrote something daft, which to my surprise worked.

class A
{    public:
        void print()
        {
            std::cout << "You can't/won't see me !!!" << std::endl;
        }  
        A* get_me_the_current_object()
        {
            return this;
        }
};  
int main()
{
    A* abc = dynamic_cast<A*>(abc);
    abc->print();
}

Here, A* abc = dynamic_cast<A*>(abc), I am doing dynamic_cast on a pointer, which isn't declared. But, it works, so I assumed that the above statement is broken as:

A* abc;
abc = dynamic_cast<A*>(abc);

and therefore, it works. However, on trying some more weird scenarios such as:

A* abc;
abc->print();

and, further

A* abc = abc->get_me_the_current_object(); 
abc->print();

I was flabbergasted, looking at how these examples worked and the mapping was done.
Can someone please elaborate on how these are working? Thanks in advance.

役に立ちましたか?

解決

You've made the common mistake of thinking that undefined behaviour and C++ bugs mean you should expect to see a dramatic crash or your computer catching fire. Sometimes nothing happens. That doesn't mean the code "works", because it's still got a bug, it's just that the symptoms haven't shown up ... yet.

But, it works, so I assumed that the above statement is broken as:

Yes, all you're doing is converting an uninitialized pointer to the same type, i.e. no conversion needed, so the compiler does nothing. Your pointer is still the same type and is still uninitialized.

This is similar to this:

int i = i;

This is valid according to the grammar of C++, because i is in scope at that point, but is undefined because it copies an uninitialized object. It's unlikely to actually set your computer on fire though, it appears to "work".

Can someone please elaborate on how these are working?

Technically you're dereferencing an invalid pointer, which is undefined behaviour, but since your member functions don't actually use any members of the object, the invalid this pointer is not dereferenced, so the code "works" (or at least appears to.)

This is similar to:

void function(A* that)
{
    std::cout << "Hello, world!\n";
}
A* p;
function(p);

Because the that pointer is not used (like the this pointer is not used in your member functions) this doesn't necessarily crash, although it might do on implementations where even copying an uninitialized pointer could cause a hardware fault. In your example it seems that your compiler doesn't need to dereference abc to call a non-static member function, and passing it as the hidden this parameter does not cause a hardware fault, but the behaviour is still undefined even though it doesn't fail in an obvious way such as a segfault..

他のヒント

abc is uninitialized and points to an undefined location in memory, but your methods don't read anything from *this so they won't crash.

The fact that they won't crash is almost certainly implementation defined behavior though.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top