views:

85

answers:

4
class someClass
{
public:
    int* ptr2Int;
};

Is this a valid class (yes it compiles)? Provided one assigns a value to ptr2Int before dereferencing it, is the class guaranteed to work as one would expect?

+2  A: 

Yes, it's fine. The pointer itself exists, just its value is just unknown, so dereferencing it is unsafe. Having an uninitialized variable is perfectly fine, and pointers aren't any different

Michael Mrozek
+1  A: 

Yes, this is exactly the same as a struct with a single uninitialized pointer, and both are guaranteed to work just fine (as long as you set the pointer before any use of it, of course).

Alex Martelli
+1  A: 

Until you dereference the pointer it's all good, then it's undefined territory.

Some compilers will set pointers to default values (like null) depending if you compile in debug or release mode. So things could work in one mode and suddenly everything falls apart in another.

David
+3  A: 

An uninitialized pointer inside a class is in no way different from a standalone uninitailized pointer. As long as you are not using the pointer in any dangerous way, you are fine.

Keep in mind though that "dangerous ways" of using an uninitialized pointer include a mere attempt to read its value (no dereference necessary). The implicit compiler-provided copy-constructor and copy-assignment operators present in your class might perform such an attempt if you use these implicit member functions before the pointer gets assigned a valid value.

Actually, if I'm not mistaken, this issue was a matter of some discussion at the level of the standardization committee. Are the implicitly generated member functions allowed to trip over trap representations possibly present in the non-initialized members of the class? I don't remember what was the verdict. (Or maybe I saw that discussion in the context of C99?)

AndreyT
Why is simply reading an uninitialized pointer 'dangerous'?
Omnifarious
@Omnifarious: Because it might contain a so called *trap representation*, which may, for example, crash the program on a mere attempt to read it. In fact, reading an ordinary uninitialized `int` can result in the same thing. But with an `int` it would take a rather exotic platform. With pointers the trap is much more real, since some hardware platforms use dedicated *address registers* to work with pointers. And these registers might perform the check of the pointer validity "on the fly". I.e. just loading the value into the register causes the trap. No dereference necessary.
AndreyT
@Omnifarious: Of course, the shorter answer is: because the language specification clearly states that reading uninitialized values of *any* type (with the exception of `unsigned char`) generally leads to undefined behavior.
AndreyT