class CBase
{
int i;
public:
void f() { std::cout<<"CBase::f"<<std::endl;}
};
And after that you write the following code somewhere:
CBase* p = NULL;
p->f();
This is an undefined behavior by the Standard. But sometimes it works. Visual Studio 2008, for example, generates a working code. The function call is resolved during the compilation, we don't use this. And you remain oblivious for a long period of time. Here is a scarier looking example
((CBase*)0)->f();
But when you try to use this pointer, you program "crashes". Examples:
class CBase
{
int i;
public:
virtual void f() { std::cout<<"CBase::f"<<std::endl;}
};
class CBase
{
int i;
public:
void f() { std::cout<<"CBase::f"<<std::endl; i=0;}
};
All this leads to very interesting, hard to find bugs.
Links:
comp.lang.c++.moderated - Functions that don't use this, called with uninitialized pointers
3 comments:
hmm never had that specific problem before, but I can see how it will be an odd bug to figure-out if it were to happen in practice.
Thanks for the tip.
cottonvibes
Thanks for the tip
You're welcome! :-)
If function does not use this pointer shouldn't it be static? I really don't see any problem in calling such function with zero pointer. Can you describe "hard-to-find" bug scenario?
Post a Comment