Pointing to a pointer in a safe manner

Given the following code snippet:

class Base
{
public:
   virtual ~Base() = default;
};

class Derived : public Base { };

int main(void)
{
  Derived d;
  Base* pb = &d;
  Base** ppb = &pb;

  Derived** ppd = ...; // Can this be defined in a type-safe manner?

  return 0;
}

Is it possible to give an expression of a type safe for assignment ppdwithout introducing an intermediate type variable Derived*?

+4
source share
2 answers

AFAIK without pointing Derivedto d. A pointer Baseto d( pb) has already lost type information through an abstraction that cannot be restored without a dangerous throw.

Since you are declaring a pointer to a pointer to Derived, you first need to point to a pointer to Derived. For instance:

Derived* pd = &d;
Derived** ppd = &pd;

Both of these definitions are type safe, checked at compile time.

+3

ppd, Derived*?

, :

Derived** ppd = nullptr;

: . , Derived** , - Derived*. Derived*, , .

: Base* Derived*, Base** Derived** , , Base* Derived*.

+1

Source: https://habr.com/ru/post/1678446/


All Articles