Re: Dereferencing a null-pointer allowed?
On May 8, 8:13 am, Lutz Richter <l...@gmx.li> wrote:
Hi,
given the following code:
-----------------------------
class B
{
public:
B(): Value(99) {}
int Get() { if (this) return Value; else return -1; }
private:
int Value;
};
int main()
{
B* b = 0;
cout << b->Get();}
-----------------------------
I wonder if this is allowed. I did not have any problem with any
compiler yet. It works! But is this guaranteed?
Unfortunately Stroustrop & Co. do not mention this problem in their
books. If anyone has a documentation about NOT doing the above example,
then please tell me.
Thanks in advance, Lutz.
No, as already mentioned - its undefined behaviour.
The pointer B* b is just a pointer, it points to a 'black hole' (tm)
until such time that the pointer's value is made to point to an object
(that means a ctor was invoked one way or another).
B* p_b; // does not invoke a ctor
Your code *should* be generating a segmentation fault, and it would if
you remove the if condition. Bypassing the compiler's ability to help
you code is bad karma.
#include <iostream>
class B
{
...
public:
B(): value(99) { std::cout << "B()\n"; }
B(const B& copy)
{
Value = copy.Value;
std::cout << "B copy ctor\n";
}
...
};
and there is no need to 'new' anything either:
int main
{
B b; // invokes ctor
B* p_b = &b;
std::cout << p_b->Get() << std::endl;
}