3

Wondering if anyone can explain why unique_ptr is breaking inheritance accessor, for instance:

class Base {

};

class Derived : private Base {

};

int main() {
    Base* pointer = new Derived;
    return 0;
}

This will correctly cause a compile time error, because Derived is inheriting from Base using private keyword. So no one outside of Derived should know the relationship between Derived and Base. But if I do:

unique_ptr<Base> pointer = unique_ptr<Base>(new Derived);

Instead of:

Base* pointer = new Derived;

The code compiles and runs fine...

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    As an aside, both error as expected under clang. I would hazard a guess that VS is just not implementing the rules properly. – Bill Lynch Dec 04 '14 at 14:54
  • 2
    This is a compiler bug. `unique_ptr(new Derived)` is a functional cast, which means the same thing as a C-style cast, and C-style casts that resolve to `static_cast` are supposed to bypass accessibility. However, your compiler incorrectly also lets C-style casts that resolve to a constructor call, where that constructor call involves a `static_cast`, bypass accessibility. I know this has been asked before, I'm trying to find a link. –  Dec 04 '14 at 14:54
  • It also errors correctly on g++, even with a very clear error-message: "error: ‘Base’ is an inaccessible base of ‘Derived’" – filmor Dec 04 '14 at 14:56
  • 1
    As @hvd suggests, this isn't specific to `unique_ptr`. `struct foo { foo(Base*) {} }; foo(new Derived);` also compiles, while `void f(Base*) {} ... f(new Derived);` does not. – dlf Dec 04 '14 at 14:57

0 Answers0