12

このような場合にポインターを比較する際のベスト プラクティスに関する情報が欲しいです。

class Base {
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = b == d;
// Or, bool theSame = dynamic_cast<Derived*>(b) == d?
4

2 に答える 2

5

任意のクラス階層を比較したい場合、安全な方法は、それらを多形にして使用することです。dynamic_cast

class Base {
  virtual ~Base() { }
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = dynamic_cast<void*>(b) == dynamic_cast<void*>(d);

static_castまたは派生クラスから基本クラスへの暗黙の変換を使用できない場合があることを考慮してください。

struct A { };
struct B : A { };
struct C : A { };
struct D : B, C { };

A * a = ...;
D * d = ...;

/* static casting A to D would fail, because there are multiple A's for one D */
/* dynamic_cast<void*>(a) magically converts your a to the D pointer, no matter
 * what of the two A it points to.
 */

が仮想的に継承されている場合A、どちらにもstatic_castすることはできませんD

于 2011-04-14T11:59:42.403 に答える
5

上記の場合、キャストは必要ありません。単純なもので機能しBase* b = d;ます。次に、現在比較しているようにポインタを比較できます。

于 2011-04-14T11:49:53.880 に答える