函数返回空集

Ian*_*ist 1 c++

我有以下功能:

ItemSet* Library::itemsForKeyword(const string& keyword)
{
    ItemSet temp;

    for(it=bookList.begin();it!=bookList.end();it++){
        if(it->getPtr()->findKeyWord(it->getPtr()->keywordsList, keyword))
            temp.insert(*it);
    }

    ItemSet* temp2 = &temp;
    return temp2;
}
Run Code Online (Sandbox Code Playgroud)

ItemSet是一个包含ItemPtr实例的集合,其中包含指向派生类实例的指针.'it'是在Library中定义的迭代器,findKeyWord是一个函数,它将keywordsList与关键字进行比较,以确定该关键字是否在该列表中.如果它返回true,则我取消引用迭代器,并将当前迭代的实例添加到temp.我的问题是,当它完成循环时,我返回temp2,但它返回空,并在我的打印功能打印时导致错误.为什么它变回空?谢谢.

Naw*_*waz 6

您将返回一个指向本地对象的指针,该对象在从函数返回时会被销毁.这肯定是未定义的行为.

另外,我不明白你为什么需要返回指针.你可以返回对象本身:

ItemSet Library::itemsForKeyword(const string& keyword)
{
   ItemSet temp;
   //your code
   return temp;
}
Run Code Online (Sandbox Code Playgroud)

如果你需要返回指针,那么我建议你返回智能指针,而不是原始指针.

std::unique_ptr<ItemSet> Library::itemsForKeyword(const string& keyword)
{
   std::unique_ptr<ItemSet> temp(new ItemSet());
   //your code, use this syntax =>  temp->insert(*it);
   return std::move(temp);
}
Run Code Online (Sandbox Code Playgroud)