我有一个有N个受保护成员的抽象类:
class Something {
protected:
UINT someVal;
std::vector<SomeType> g_MyVec;
// some virtual abstract methods ...
public:
UINT getSomeVal() { return someVal; }
std::vector<SomeType> GetVec() { return g_MyVec; }
}
class SubClass : public Something {
public:
SubClass() { // no members in this class, all inherited from super
someVal = 5; // this sticks
g_myVec = { .. correct initialization }; // this doesn't stick
}
}
此代码的客户端执行:
Something* s = &SubClass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec(); // Nada, it returns 0 size, nothing at all... WHY?!
非常感谢启蒙运动。
答案 0 :(得分:4)
你正在拿一个临时的地址。这是一个UB
和错误的代码。在;
正确的方法是(假设没有C ++ 11):
Something* s = new Subclass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec();
delete s;