I found very strange behavior of std::unique_ptr
in Visual Studio 2013 and 2017. Let's consider an example:
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
Note that inheritance is private. This example compiles only on Visual Studio. Moreover, the virtual function call works because it is public inheritance. So we have encapsulation violation since the cast from Derived
to Base
should be inaccessible. Can anybody explain why Visual Studio allows this? Is it a known issue?
The line below doesn't compile for reasonable causes. The only difference between the first and second usages is in the second, the named object B
is created.
std::unique_ptr<Base> B(new Derived()); // Doesn't compile
Is it related somehow with this issue which still isn't fixed?
Foo(std::unique_ptr<Base>(new Derived())); // Compiles
cannot appear outside of a function. I would recommend updating the code to contain a MCVE – Chophouse