C ++ default constructor not initializing nullptr pointer?

I wonder if I have an A* member in my class, should we not automatically set nullptr if I have my class constructor in this form:

 class MyCLass { A* m_pointer; public: MyCLass() { } }; 

Does it matter if I do MyCLass* o = new MyCLass; , or I'm doing MyCLass* o = new MyCLass(); in c ++ 11?

+5
source share
2 answers

Pointers are "POD types" ... aka "Plain old data." Here are the rules for when and where they are initialized by default:

Initializing Default POD Types in C ++

So no. It doesn't matter what your constructor is for a class if it is a raw pointer as a member of the class. You are not actually instantiating the class. That way, members like Foo * or std::vector<Foo> * or anything that ends with * will not be initialized to nullptr.

Smart pointer classes are not PODs. Therefore, if you use unique_ptr<Foo> or shared_ptr<Foo> , which creates instances of classes that have a constructor, which makes them effectively null if you do not initialize them.

Does it matter if I do MyCLass * o = new MyCLass; or am I doing MyCLass * o = new MyCLass (); in c ++ 11?

One question per question, please.

Are parentheses made after the type name with a new one?

+14
source

The default constructor, if generated by the compiler or default, will initialize all members by default. Any custom constructor similarly initializes by default all members that do not have an explicit initializer in the initializer list.

By default, initialize means "call the default constructor for classes, leave everything else uninitialized."

+1
source

Source: https://habr.com/ru/post/1203797/


All Articles