让我困惑的是,为什么Foo *foo = new Foo(5);
编译,而std::make_shared<Foo>(5)
不编译?
下面是代码片段。请注意代码片段中的注释
#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::Foon"; }
public:
~Foo() { std::cout << "Foo::~Foon"; }
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();
}
静态函数仍然是类的成员,因此可以访问私有部分。