Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: member pointer initialised?

Code sample should explain things:

class A
{
    B* pB;
    C* pC;
    D d;

    public : 
    A(int i, int j) : d(j)
    {
        pC = new C(i, "abc");
    } // note pB is not initialised, e.g. pB(NULL)

    ...
};

Obviously pB should be initialised to NULL explicitly to be safe (and clear), but, as it stands, what is the value of pB after construction of A? Is it default initialised (which is zero?) or not (i.e. indeterminate and whatever was in memory). I realise initialisation in C++ has a fair few rules.

I think it isn't default initialised; as running in debug mode in Visual Studio it has set pB pointing to 0xcdcdcdcd - which means the memory has been new'd (on the heap) but not initialised. However in release mode, pB always points to NULL. Is this just by chance, and therefore not to be relied upon; or are these compilers initialising it for me (even if it's not in the standard)? It also seems to be NULL when compiled with Sun's compiler on Solaris.

I'm really looking for a specific reference to the standard to say one way or the other.

Thanks.

like image 980
DDD Avatar asked Jul 17 '09 16:07

DDD


2 Answers

Uninitialised pointers are allow to basically contain a random value, although some compilers tend to fill them with 0 or some other recognisable value, especially in debug mode.

IMHO this is due to C++'s "don't pay for what you don't use" design. If you don't consider it important, the compiler does not need to go through the expense of initialising the variable for you. Of course, once you've chased a random pointer you might find it prudent to initialise it the next time around...

like image 122
Timo Geusch Avatar answered Sep 30 '22 02:09

Timo Geusch


Here is the relevant passage fromt he standard:

12.6.2 Initializing bases and members [class.base.init]

4 If a given nonstatic data member or base class is not named by a mem-
initializer-id in the mem-initializer-list, then

--If the entity is a nonstatic data member of (possibly cv-qualified) class type (or array thereof) or a base class, and the entity class is a non-POD class, the entity is default-initialized (dcl.init). If the entity is a nonstatic data member of a const-qualified type, the entity class shall have a user-declared default constructor.

--Otherwise, the entity is not initialized. If the entity is of const-qualified type or reference type, or of a (possibly cv-quali- fied) POD class type (or array thereof) containing (directly or indirectly) a member of a const-qualified type, the program is ill- formed.

After the call to a constructor for class X has completed, if a member

of X is neither specified in the constructor's mem-initializers, nor
default-initialized, nor initialized during execution of the body of
the constructor, the member has indeterminate value.

like image 26
Greg Rogers Avatar answered Sep 30 '22 01:09

Greg Rogers