jeudi 9 juin 2022

Returning a shared_ptr instance of an object whose constructor is marked as private

What confuses me is that why Foo *foo = new Foo(5); compiles, whereas std::make_shared<Foo>(5) does not compile?

Here is the code snippet. Please pay attention to the comment in the code snippet.

#include <iostream>
#include <memory>
 
class Foo {
private:     //the user should not construct an instance through the constructor below.                    
    Foo(int num):num_(num) { std::cout << "Foo::Foo\n"; }
public:
    ~Foo() { std::cout << "Foo::~Foo\n"; } 
    static std::shared_ptr<Foo> Create() {
        #if WORKS_WELL
        Foo *foo = new Foo(5);  //Why this works?  The constructor is private indeed.
        return std::shared_ptr<Foo>(foo);
        #else
        return std::make_shared<Foo>(5);
        #endif
    }
private:
    int num_;
};
 
int main() {
    auto pf = Foo::Create(); 
}

Aucun commentaire:

Enregistrer un commentaire