我不太确定如何提出我的问题,所以我会尽量保持简洁,并要求大家耐心等待。
主要:
MovieStore ctr{ repo };
MovieStoreGUI gui{ ctr };
MovieStore类(ctr):
class MovieStore {
Repo& repo;
public:
MovieStore(RepoAbstract& rep) noexcept :rep{ rep }{}
const vector<Movie>& getAll() const
{
return rep.getAll();
}
存储库类:
class Repo{
protected:
vector<Movie> all;
public:
vector<Movie> getAll(){return all;}
这是我要实现此人的课程:
class MovieStoreGUI{
private:
MovieStore& ctr;
void reloadList(vector<Movie>);
public:
MovieStoreGUI(MovieStore& ctr) : ctr{ ctr } {
reloadList(ctr.getAll()); // here is the problem
}
};
My problem: I can't send the vector that contains the Movies in the reloadList function, no matter what I do, it arrives as an empty vector in the function ( { size = 0 } in debugger ). I also tried ctr.getAll().size()
in main and it shows the correct value , but here it's a different story.
I don't know if I shared enough info on this bug, so please ask for more context if it is necessary.
你的问题是
Here you are returning a reference to
rep.getAll()
, butrep.getAll()
is a temporary object. That means when the return statement ends that the returned vector is destroyed and you are left with a reference to a vector that no longer exists.To fix this you either need to make
Repo::getAll()
return a reference, or makeMovieStore::getAll()
return by value.