将派生 class 转换为 std::make_shared 中受保护的基接口时出错
Error when casting derived class to protected base interface in std::make_shared
我有这个代码:
#include <memory>
class SomeInterface {
public:
virtual void VirtualMethod() {}
virtual void PureVirtualMethod() = 0;
};
class SomeInterfaceDependent {
public:
explicit SomeInterfaceDependent(SomeInterface* a) : a_(a) {}
private:
SomeInterface* const a_;
};
class Implementation : protected SomeInterface {
public:
void Init() {
// Ok
auto raw = new SomeInterfaceDependent(this);
// Cannot cast 'Implementation' to its protected base class 'SomeInterface'.
auto shared = std::make_shared<SomeInterfaceDependent>(this);
// Ok
SomeInterface* casted_some_interface = this;
auto shared2 = std::make_shared<SomeInterfaceDependent>(casted_some_interface);
}
protected:
void PureVirtualMethod() override {}
};
int main() {
Implementation i;
i.Init();
return 0;
}
C++ 标准 17,编译器 GCC。
当(和):
时出现错误 error: ‘SomeInterface’ is an inaccessible base of ‘Implementation’
- SomeInterface 使用受保护的访问修饰符继承。
- SomeInterfaceDependent 使用
std::make_shared
. 创建
- SomeInterface 隐式转换。
为什么?是 std::make_shared
错误吗?
受保护的继承不是 public 到外部 类。
因此,编译器看不到 Implementation 继承自 SomeInterface,并且会说它不能进行转换。
Is it the std::make_shared bug?
没有
Why?
std::make_shared
不是 Implementation
的友元,因此它无法访问其非 public 基,因此它无法隐式转换指针。
我有这个代码:
#include <memory>
class SomeInterface {
public:
virtual void VirtualMethod() {}
virtual void PureVirtualMethod() = 0;
};
class SomeInterfaceDependent {
public:
explicit SomeInterfaceDependent(SomeInterface* a) : a_(a) {}
private:
SomeInterface* const a_;
};
class Implementation : protected SomeInterface {
public:
void Init() {
// Ok
auto raw = new SomeInterfaceDependent(this);
// Cannot cast 'Implementation' to its protected base class 'SomeInterface'.
auto shared = std::make_shared<SomeInterfaceDependent>(this);
// Ok
SomeInterface* casted_some_interface = this;
auto shared2 = std::make_shared<SomeInterfaceDependent>(casted_some_interface);
}
protected:
void PureVirtualMethod() override {}
};
int main() {
Implementation i;
i.Init();
return 0;
}
C++ 标准 17,编译器 GCC。
当(和):
时出现错误error: ‘SomeInterface’ is an inaccessible base of ‘Implementation’
- SomeInterface 使用受保护的访问修饰符继承。
- SomeInterfaceDependent 使用
std::make_shared
. 创建
- SomeInterface 隐式转换。
为什么?是 std::make_shared
错误吗?
受保护的继承不是 public 到外部 类。
因此,编译器看不到 Implementation 继承自 SomeInterface,并且会说它不能进行转换。
Is it the std::make_shared bug?
没有
Why?
std::make_shared
不是 Implementation
的友元,因此它无法访问其非 public 基,因此它无法隐式转换指针。