我在Visual Studio2013和2017中发现了std::unique_ptr非常奇怪的行为。让我们来看一个例子:
class Base
{
public:
virtual ~Base() = default;
virtual void Foo() = 0;
};
class Derived : private Base
{
public:
void Foo() override
{
std::cout << "Foo";
}
};
void Foo(std::unique_ptr<Base> a)
{
a->Foo();
}
Foo(std::unique_ptr<Base>(new Derived())); // Compiles请注意,继承是私有的。此示例仅在Visual Studio上编译。此外,虚函数调用之所以起作用,是因为它是公共继承。所以我们有封装冲突,因为从Derived到Base的转换应该是不可访问的。有人能解释为什么Visual Studio允许这样做吗?这是一个已知的问题吗?
由于合理的原因,下面的代码行不能编译。第一次用法和第二次用法之间的唯一区别是在第二次用法中,创建了命名对象B。
std::unique_ptr<Base> B(new Derived()); // Doesn't compile它是不是与this issue有某种关系,它仍然没有得到修复?
发布于 2018-09-28 07:03:34
这在cl版本19.15.26726 (VS 2017 v15.9.0-pre.1.0)中已修复:
Foo(std::unique_ptr<Base>(new Derived()));给出
error C2243: 'type cast': conversion from 'Derived *' to 'Base *' exists, but is inaccessiblehttps://stackoverflow.com/questions/43528976
复制相似问题