C++ default constructor does not initialize pointe

2020-08-26 11:00发布

问题:

I wonder if I have a A* member in my class, shouldn't it we set to nullptr automatically if I have a constructor of my class in this form:

class MyCLass
{
    A* m_pointer;

public:
    MyCLass()
    {
    }
};

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

回答1:

Pointers are "POD types"...a.k.a. "Plain Old Data". The rules for when and where they are default-initialized are summarized here:

Default initialization of POD types in C++

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

The smart pointer classes are not POD. So if you use a unique_ptr<Foo> or a shared_ptr<Foo> that is creating instances of classes, that do have a constructor that makes them effectively null if you do not initialize them.

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

One question per question, please.

Do the parentheses after the type name make a difference with new?



回答2:

The default constructor, if compiler-generated or defaulted, will default-initialize all members. Any user-defined constructor will similarly default-initialize all members that don't have an explicit initializer in the initializer-list.

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



标签: c++