简体   繁体   中英

c++ class member initialization without constructor

Can someone explain me how the memory allocation and initialization in c++ works?

File Test.h
-----------
class Test
{
    public:
        Test();

        void clearSet();

    private:
        std::set<std::string> m_SetStringMember;
        int m_initMe;
}

File Test.cpp
-------------

Test::Test():m_initMe(0)
{}

Test::clearSet()
{
    m_SetStringMember.clear(); 
}

What I do understand is:
The int member m_initMe is correctly initialized in the constructor and therefore has a valid adress in memory and a valid value.
But what happens with the m_SetStringMember ?
Does it has to have a valid adress in memory?
Does it has to have a valid default value?
Set by the default constructor of std::set<std::string>() ?
Or do I have to explicitly set m_SetStringMember = std::set<std::string>() in the constructor?

But what happens with the m_SetStringMember? Does it has to have a valid address in memory?

Yes, but the address has nothing to do with the constructor. The constructor only initialises an object once it has been given a valid address by the compiler or by the heap allocator.

Does it has to have a valid default value?

Yes

Set by the default constructor of std::set()?

Yes

Or do I have to explicitly set m_SetStringMember = std::set() in the constructor?

If you want to be explicit do this

Test::Test() : m_initMe(0), m_SetStringMember() {}

but it the same thing would happen by default oo.

m_SetStringMember is an object of a class std::set that has it's own constructor. It's correctly initialized by its constructor.

One more addendum to John's correct post:

The order in which those variables will initialize is the order in which they are declared, so actually if you wanted to be explicit you should do this:

Test::Test() : m_SetStringMember(), m_initMe(0)  {}

Making sure the order in your initialization list matches the order in which you declared them is a good practice to get into, and you can even have the compiler warn you. A lot of the time your variables will end up depending on each other and thus order matters.

Furthermore, if you don't specify a default value then the classes default constructor will be used (your compiler will generate one for you if you don't create it, and assuming it's available, ie doesn't have any access restrictions) -- side note: check out the rule of 3 on a common policy for creating c++ class constructors. If the variable is a POD (plain old data type -- ints, floats, etc.) then it will default to 0.

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