不,這是不安全的,因爲當銷燬QObject
時,QPointer<T>
可能會更改爲NULL
。 (QPointer
類似於std::weak_ptr
)。所以這個代碼將產生不確定的行爲:
class CopyableWidget : public QWidget {
Q_OBJECT;
public:
CopyableWidget(Widget* parent = 0) : QWidget(parent) {}
CopyableWidget(const CopyableWidget& w, Widget* parent = 0) : QWidget(parent) {}
};
std::vector<CopyableWidget> v(2); // Two default-constructed widgets
std::map<QPointer<CopyableWidget>, int> wid_values;
wid_values[&v[0]] = 1;
wid_values[&v[1]] = 2;
// wid_values contains { {&v[0], 1}, {&v[1], 2} }
v.resize(1);
// The QPointer in wid_values constructed from &v[1] now acts like NULL.
// wid_values contains { {&v[0], 1}, {NULL, 2} }
// But &v[0] > NULL (on most platforms). Class invariant was violated!
相關:?允許在有序的STL容器鍵指針(http://stackoverflow.com/questions/4913161/) – 2011-03-08 21:37:49