I discovered something playing with QtCreator and bugs I was having in a destructor working with gcc: pointers are not equal to NULL by default; this needs to be added manually (to the constructor in my case). Is this right? How come? What's their default value?
Asked
Active
Viewed 580 times
0
-
7That's the case for *all* pointers in C++. If you want them NULL, assign them. – Mark Ransom Dec 11 '13 at 00:01
-
2Most compilers would emit a warning if you fail to initialize a variable. Treat warnings as errors, and you've got yourself 'covered'. – ChristopheD Dec 11 '13 at 00:06
-
@MarkRansom : Well I can assure you that a pointer defined without _initialization_ would pass the test my_pointer == NULL with gcc. I thought that this was the C++ standard. Thank you for clarifying ;) – Liam Dec 11 '13 at 00:08
-
2@Liam: actually, no. It *may* be `NULL` in very particular conditions - e.g. if it's allocated on the stack in a yet unused stack portion or if it's allocated from a new block of memory from the heap, all of this if "debug allocators" (which deliberately mark memory with a pattern to avoid hiding these errors) aren't involved. – Matteo Italia Dec 11 '13 at 00:11
-
1@MatteoItalia: Or the more common condition of static storage duration, in which it's guaranteed. – MSalters Dec 11 '13 at 08:06
-
1@ChristopheD: "Most compilers would emit a warning if you fail to initialize a variable" - not for class members, at least I've never seen such a warning. It'd be fantastic if there was one for MSVC, gcc or clang. – Frank Osterfeld Dec 11 '13 at 12:32
2 Answers
5
Pointers, as every other primitive type, start living uninitialized, which means that they may have any value (actually, it's undefined behavior to read from any uninitialized variable).
On the other hand, the constructor for structs and classes is guaranteed to run on creation of a class instance, which means that, if it is written correctly, the class starts living in a valid state.

Matteo Italia
- 123,740
- 17
- 206
- 299
-
3The truth is that it depends on compiler implementation. But as the standard says nothing about initialization... (except on static variables, I believe). [This](http://stackoverflow.com/a/2218275/2651145) has more info on initialization. – Doktoro Reichard Dec 11 '13 at 00:02
1
Unless a constructor in place, there are no default values
Looking at int * x;
x
has an undefined value
std::string is refers to a class with a contructor so with std::string x
there is a defined value for x
: "empty string constructor (default constructor) Constructs an empty string, with a length of zero characters."

Glenn Teitelbaum
- 10,108
- 3
- 36
- 80