c++ - 标准授权 enable_shared_from_this 是否公开继承?为什么?

标签 c++ c++11 language-lawyer libstdc++ libc++

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 + friend shared_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/

相关文章:

c++ - 了解 2^31 和 -2^31 整数提升

c++ - C 中 wstring 的等价物

c++ - 如何将 "<<"与我自己的结构一起使用?

c++ - 为什么 boost lockfree freelist 大小被限制为最多 65535 个对象?

c++ - 使用点后模板函数的特化会破坏编译

java - (编译器) else if(true) vs else 场景

c++ - 有什么好的方法可以捕捉或避免这种微妙的错误吗?

c++11 - 捕获引用的一致性

c++ - 创建和管理查找容器的正确方法

c++ - C++是否保证从两个线程访问数组的相邻元素是安全的