简体   繁体   中英

Are pointers declared inside struct/class initialized to nullptr by default?

I have read on Stack Overflow that global/static variables are initialized to their default value ( 0 ).

I also read somewhere else (not sure tho), that class variables (non-static) are also initialized to 0 . Is this true?

Specifically, I am wondering whether my pointers are by default initialized to nullptr .

I tried compiling on g++ and clang and both seem to initialize them to nullptr .

#include <iostream>

struct Foo {
    int *ptr;
};

int main() {
    Foo f;
    std::cout << f.ptr;
}

printed:

0

If it's only my compiler doing it, is there any way I can tell my compiler not to do this (using some compiler flag)?

I also read somewhere else (not sure tho), that class variables (non-static) are also initialized to 0.

Wherever you read that ( if you read that), then stop reading that source!

Is this true?

No.

Here's a short example:

#include <iostream>

class Foo {
public:
    int* ip; // Do we get default initialization to "nullptr" ?? ...
    Foo() = default;
};

int main()
{
    Foo Bar;
    std::cout << Bar.ip << std::endl; // ... print the "ip" pointer to see!
    return 0;
}

The output when building with clang-cl and running on Windows 10 is (but the actual value varies):

00000272B7D941D0

When compiling with MSVC, the following message is given:

warning C4700: uninitialized local variable 'Bar' used

Of course, some compilers may set such uninitialized memory to zero, and even when built with Clang or MSVC, as above, the initial value of the pointer may occasionally just happen to be zero. However, the warning from MSVC should be taken seriously. Furthermore, the static analyser that clang-cl uses gives a more specific warning:

std::cout << Bar.ip << std::endl;
^
warning GDEC5F24A: 1st function call argument is an uninitialized value [clang-analyzer-core.CallAndMessage]

is there any way I can tell my compiler not to do this (using some compiler flag)?

Probably not – but you can enable all compiler warnings, which will show you cases where you have such behaviour.

Pointers are not initialized when they are instantiated. Unless a value is assigned, a pointer will point to some indeterminate value (garbage address) by default. Some compilers will assign nullptr for pointers but that's not standard so don't count on it. Always initialize raw pointers and check against null before using them.

Moreover, structs and classes are interchangeable. Of course, a struct default visibility for its members is public while class attributes are private.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM