lundi 24 octobre 2016

Constructor Initializer List in C++

Please first look the code as follow:

class StrBlod
{
    StrBlob();
    ....
    private:
        std::shared_ptr<std::vector<std::string> > data;
}
//initializer empty into data ;

StrBlob::StrBlob()
// : data(std::make_shared<std::vector<std::string> >())      // compile success
{
 //  data(std::make_shared<std::vector<std::string> >());     // compile error
}
int main()
{
    // this statement can compile
    std::shared_ptr<std::vector<std::string> >data(std::make_shared<std::vector<std::string> >());
    return 0;
}

I want to know why the statement above compiles occurs error? ?

error: no match for call to ‘(std::shared_ptr > >) (std::shared_ptr > >)’ data(std::make_shared >());

corresponding knowledge quoted in C++Primer 5th (Chapter 7.5) as follow. We can often, but not always , ignore the distinction between whether a member is initialized or assigned. Members that are const or references must be initialized. Similarly, members that are of a class type that does not define a default constructor also must be initialized

first I will share my thought.the 'data' member is default initialized before the constructor body starts executing. right? so,the 'data' member inside constructor will copy the object created from the function make_shared.right?

Aucun commentaire:

Enregistrer un commentaire