从 enable_shared_from_this
继承是很常见的,只是为了能够从成员函数返回 shared_ptr
作为主要目的,而不是暴露 enable_shared_from_this
派生类中的 API。
由于要使用 enable_shared_from_this
必须通过公共(public)继承来实现(标准是否强制要求这样做?理由是什么?),这是无法实现的并且 enable_shared_from_this
API 被强制进入派生类公共(public) API。
私下继承 enable_shared_from_this
并使 shared_ptr
成为友元类可以在 clang 上与 libc++ 结合使用,但不适用于 stdlibc++。
既然 private enable_shared_from_this
+ friend shared_ptr
(或 protected 继承)似乎涵盖了这个用例,那么它是否足以作为适合的解决方案的标准“从这个共享”问题?
最佳答案
Since
private enable_shared_from_this
+ friendshared_ptr
seems to cover this use case, shouldn't it be sufficient by the standard?
没有。该标准允许实现在实现事物的方式上有很大的自由度。 shared_ptr<T>
的构造函数采用一个对象的 shared-from-this 东西可能会推迟到某个辅助函数或其他对象。最讽刺的是,它可以遵循 shared_ptr<T>
的基类。 ;)
因此,enable_shared_from_this
必须可以通过任何代码访问,以便 shared_ptr
构造函数工作。
关于c++ - 标准授权 enable_shared_from_this 是否公开继承?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165889/