Я пытаюсь поддерживать вектор быстрого доступа следующим образом:
МойКласс.h:
class MyClass{
private:
std::vector<Stuff> myStuffList;
std::tr1::unordered_map<std::string,Stuff*> myStuffListIndex;
...
public:
void addToStuffList(std::string key,Stuff stuff);
};
MyClass.cpp:
...
void MyClass::addToStuffList(std::string name, Stuff stuff){
myStuffList.push_back(stuff);//our man is guaranteed to be at tail
myStuffListIndex[name] = &myStuffList[myStuffList.size()-1];//store
//pointer to object that we just copy-constructed at tail of list
}
Материал.ч:
class Stuff{
private:
std::string name;
public:
Stuff();
Stuff(const Stuff&);
Stuff& operator=(const Stuff&);
...
};
Stuff.cpp:
Stuff::Stuff() : name(""){}
Stuff::Stuff(const Stuff& other){
if(this != &other){
this->name = other.name;
}
}
Stuff& Stuff::operator=(const Stuff& other){
if(this != &other){
this->name = other.name;
}
}
std::string Stuff::getName(){
return name;//exc_bad_access triggered here
}
Позже, когда я пытаюсь получить доступ к элементам из вектора через карту, я получаю явно прерывистую ошибку exc_bad_access следующим образом:
void methodA(){
Stuff localStuff;
myClassInstance.addToStuffList("mostrecentstuff",localStuff);
}
...
void methodB(){
//different method now, localStuff would be out of scope but
//shouldn't matter since we passed by value in addToStuffList, right?
Stuff* pStuff = myStuffListIndex["mostrecentstuff"];
std::cout << "Hello, my name is " << pStuff->getName() << std::endl;
}
int main(int argc, const char* argv[]){
methodA();
methodB();
}
Почему доступ к pStuff->getName() вызывает ex_bad_access?
Stuff
? - person PaulMcKenzie   schedule 27.01.2015push_back
, эти указатели могут стать недействительными. - person PaulMcKenzie   schedule 28.01.2015