As the title says, if I cast a pointer to a base class, to a derived class, when the pointer is null, is it a safe operation from the point of view of the C++11/C++14 standard?
struct base
{
virtual ~base() = default;
};
struct derived : base {};
struct wrapper
{
using allowed_derived_t = derived;
base* base_ptr = nullptr;
void set_ptr(base* ptr)
{
if (!dynamic_cast<allowed_derived_t*>(ptr))
throw std::logic_error("Check your user code");
base_ptr = ptr;
}
allowed_derived_t* ptr() const
{ return static_cast<allowed_derived_t*>(base_ptr); }
};
Is it the ptr()
method safe, if I call it before calling set_ptr
? Because, before setting the pointer, the base_ptr
is not of the required type (allowed_derived_t
), however, the dynamic pointed-to object isn't either of the wrong type (because there's no pointed-to object).
What does the standard say in that situation?