dimanche 21 octobre 2018

No matching constructor for initialisation of const std::shared_ptr<>

Scenario
I am using C++ 17 on MacOS with clang as compiler. I have class as below

ClassA.h

ClassA {

public:
    ClassA(const std::shared_ptr<SomeClass> & some_class);

private:
    std::shared_ptr<SomeClass> m_some_class;
}

ClassA.cpp

ClassA::ClassA(const std::shared_ptr<SomeClass> & some_class) : m_some_class(some_class) {

}

Note above that ClassA intakes a const std::shared_ptr<SomeClass> & type into its constructor and stores it as its member.

Next there is ClassB which has private member of ClassA as std::shared_ptr. And all I want to do is to initialise m_class_a by passing it the required const std::shared_ptr<SomeClass> & which ClassA needs to init its member.

ClassB.h

ClassB {

public:
    ClassB(const std::shared_ptr<SomeClass> & some_class);

private:
    std::shared_ptr<ClassA> m_class_a;
}

ClassB.cpp

ClassB::ClassB(const std::shared_ptr<SomeClass> & some_class) : m_class_a(some_class) {

}
// Above constructor throws compiler error complaining "No matching constructor for initialisation of `std::shared_ptr<SomeClass>`"

Question:
What is wrong with what I am doing above and what is reason for this compiler error? How can I resolve the issue?

Secondary question:
What would change if in ClassB, instead of having std::shared_ptr<ClassA> m_class_a as member, I would have had ClassA & m_class_a as member?

Aucun commentaire:

Enregistrer un commentaire