【问题标题】:How can shared_ptr convert to a private base class?shared_ptr 如何转换为私有基类?
【发布时间】:2014-09-25 20:10:21
【问题描述】:

在下面的继承结构中,IFace是Face的私有基类:

class IFace{};

class Face : /*private*/ IFace{};

虽然从原始Face* 到IFace* 指针的转换当然会失败,但shared_ptr<Face> 仍然可以转换为shared_ptr<IFace>,

shared_ptr<Face> s_face = make_shared<Face>();
shared_ptr<IFace> s_iface = s_face; //works

Face* p_face = new Face();
IFace* p_iface = p_face; //compiler complains (righteously) 
                         //about the base class being inaccessible

shared_ptr在这里玩什么魔术?

标准是否涵盖此行为,还是特定于我的实现 (MSVC12)?

新创建的s_iface 是否与s_face 共享其引用计数?

【问题讨论】:

  • 这在 gcc 4.8.1 上使用公共继承时成功,但在使用私有继承时 fails:"error: conversion from 'std::shared_ptr' to non-scalar类型 'std::shared_ptr' 请求”
  • Fails 也带有 clang/libc++,所以我要解决一个 MSVC 错误。
  • 我不认为这里的shared_ptr 行为是标准的,但总的来说,您可以通过 C 样式转换转换为指针或对不可访问的基的引用。这是该演员阵容的一个特例。 IE。这不是reinterpret_cast。

标签: c++ pointers inheritance c++11 type-conversion


【解决方案1】:

如果指针不可隐式转换,则标准要求转换构造函数被 SFINAE 淘汰(标准是“不应参与重载决议”)。这看起来像是 MSVC 的 std::is_convertible 实现中的一个错误:

#include <type_traits>
class IFace {};

class Face : /*private*/ IFace{};

int main() {
    static_assert(std::is_convertible<Face *, IFace *>::value, "Face * is not convertible to IFace *");
    static_assert(!std::is_convertible<Face *, IFace *>::value, "Face * is convertible to IFace *");
}

使用 MSVC12 给我error C2338: Face * is convertible to IFace *。

clang 和 g++ 在第一个 static_assert 处正确失败并报告 Face * is not convertible to IFace *。

查看 MSVC 的 &lt;type_traits&gt; 标头,is_convertible 是使用内置编译器实现的,因此归结为编译器错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-25
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多