简体   繁体   中英

C++ default constructor does not initialize pointer to nullptr?

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?

Pointers are "POD types"...aka "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?

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".

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