Background information: This was detected on Visual Studio 2008, and confirmed again on Visual Studio 2013. G++ screamed at the code, while Visual accepted the private inheritance breach silently.
So, on Visual C++, we have the following code:
class Base {};
class Derived : Base {}; // inherits privately. Adding explicitly the
// keyword private changes nothing
int main()
{
std::auto_ptr<Base>(new Derived) ; // compiles, which is NOT EXPECTED
std::auto_ptr<Base> p(new Derived) ; // Does not compile, which is expected
}
Why would the first (temporary) auto_ptr compile? I went inside it in debug, it did exactly what is was supposed to do with a public inheritance (call the right constructor, etc.)
Wondering if perhaps the issue was with the auto_ptr implementation (we never know...), I reduced the issue on this standalone code:
class Base {};
class Derived : Base {};
template <typename T>
class Ptr
{
T * m_p;
public :
Ptr(T * p_p)
: m_p(p_p)
{
}
} ;
int main()
{
Ptr<Base>(new Derived) ; // compiles, which is NOT EXPECTED
Ptr<Base> p(new Derived) ; // Does not compile, which is expected
}
Again, I expected the code to NOT compile, as Derived inherits privately from Base.
But when we create a temporary, it works.
And we can't blame it on std::auto_ptr.
Is there something in the standard (either 98 or 11 or 14) I missed, or is this a bug?
Ptr<Base>(new Derived);
does not do what it looks like it does. It looks like it creates a temporary of typePtr<Base>
constructed with anew Derived
, but it actually declares a function or some such nonsense. – PigeonheartedDerived
constructor and destructor allows to check whether there is actual code executed. – Hopehstatic_cast
: connect.microsoft.com/VisualStudio/feedback/details/540343/… – Burnleyclass Ptr
with hard-codedBase
inside yields the same behaviour. – Tamperclass Base {}; class Derived : Base {}; struct S { S(Base *) {} }; int main() { S(new Derived); }
– Tamper