在编译时验证对象创建为 shared_ptr
Verify at compile time that objects are created as shared_ptr
我写了 类(通常作为 boost::asio
的一部分),它们的对象依赖于包裹在 shared_ptr
中,因为它们使用 shared_from_this()
。如果对象未在 shared_ptr
中实例化,有没有办法阻止对象被编译?
所以,我要找的是:
std::shared_ptr<MyClass> a = std::make_shared<MyClass>(); // should compile fine
std::unique_ptr<MyClass> a = std::make_unique<MyClass>(); // compile error
MyClass a; // compile error
将其构造函数设为私有,并为其提供一个创建 shared_ptr
的静态工厂成员函数。不要忘记在评论中记录您的设计决定!
// Thing that foos the bar
struct Foo : std::enable_shared_from_this<Foo>
{
// Returns a shared_ptr referring to a new instance of Foo
static std::shared_ptr<Foo> CreateShared()
{
return std::shared_ptr<Foo>(new Foo);
}
private:
// To avoid bugs due to the shared_from_this base,
// we restrict Foo creation to being via CreateShared().
Foo() = default;
};
(我无法想象 std::make_shared
会因为 private ctor 而起作用,但你可以试试。)
不过,我不得不说,这听起来不像是 class 应该负责的事情。这是一种倒退的编程。
偷Eljay's :
In general, it is best (if possible) that objects are not self-aware if they are contained in a shared_ptr, or on the heap, or on the stack, or by pointer, or in a vector, or as a data member, or as a global. As soon as they are self-aware of how they are life-cycle managed, they become a lot more constrained. Unnecessarily so. shared_from_this
is (arguably) an anti-pattern. But... sometimes it may be a necessary anti-pattern.
我宁愿避免 enable_shared_from_this
并让人们以他们认为合适的方式使用您的 Foo
,例如通过精益 unique_ptr
.
我写了 类(通常作为 boost::asio
的一部分),它们的对象依赖于包裹在 shared_ptr
中,因为它们使用 shared_from_this()
。如果对象未在 shared_ptr
中实例化,有没有办法阻止对象被编译?
所以,我要找的是:
std::shared_ptr<MyClass> a = std::make_shared<MyClass>(); // should compile fine
std::unique_ptr<MyClass> a = std::make_unique<MyClass>(); // compile error
MyClass a; // compile error
将其构造函数设为私有,并为其提供一个创建 shared_ptr
的静态工厂成员函数。不要忘记在评论中记录您的设计决定!
// Thing that foos the bar
struct Foo : std::enable_shared_from_this<Foo>
{
// Returns a shared_ptr referring to a new instance of Foo
static std::shared_ptr<Foo> CreateShared()
{
return std::shared_ptr<Foo>(new Foo);
}
private:
// To avoid bugs due to the shared_from_this base,
// we restrict Foo creation to being via CreateShared().
Foo() = default;
};
(我无法想象 std::make_shared
会因为 private ctor 而起作用,但你可以试试。)
不过,我不得不说,这听起来不像是 class 应该负责的事情。这是一种倒退的编程。
偷Eljay's
In general, it is best (if possible) that objects are not self-aware if they are contained in a shared_ptr, or on the heap, or on the stack, or by pointer, or in a vector, or as a data member, or as a global. As soon as they are self-aware of how they are life-cycle managed, they become a lot more constrained. Unnecessarily so.
shared_from_this
is (arguably) an anti-pattern. But... sometimes it may be a necessary anti-pattern.
我宁愿避免 enable_shared_from_this
并让人们以他们认为合适的方式使用您的 Foo
,例如通过精益 unique_ptr
.