C++ 指向指针范围问题的指针

标签 c++ pointers

我有一个列表,其中存储指向对象指针的指针。我有一个函数,我在其中创建指向这些对象的指针并将它们的地址存储在列表中(因此指向指针)。然而,一旦这个函数完成,指针就不再有效(对象是指针但不是指针,因为它超出了范围)所以现在我指向指针的指针不起作用。你如何解决这个问题?

list<Actor**> lst;
void CreateEnemy()
{
    Actor* a = new Actor();

    lst.push_back(&a);
}

int _tmain(int argc, _TCHAR* argv[])
{
    CreateEnemy();
    // at this point the pointer to a pointer stored in lst isn't valid anymore because it went out of scope after CreateEnemy() completed.
}

最佳答案

这是您可以根据您的评论执行的操作的简单示例。

list<unique_ptr<Actor>> lst;

void CreateEnemy()
{
    lst.push_back(unique_ptr<Actor>(new Actor));
}

void KillRandomEnemies()
{
    for (auto& i : lst)
    {
        if (rand() % 100)
            i.reset();
    }
}    

class Projectile
{
public:
    Projectile(unique_ptr<Actor> & a)
        :actor(&a)
    {}

    bool IsTargetDead() const { return !(*actor); }

private:
    unique_ptr<Actor> * actor;
};

int main()
{
    CreateEnemy();
    Projectile proj(lst.front());

    while (something())
    {
        KillRandomEnemies();

        if (proj.IsTargetDead())
            whatever();
    }
}

关于C++ 指向指针范围问题的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332132/

相关文章:

c++ - 这个 C++ 程序中的 MPI_Bcast() 是做什么用的?

c++ - C++ std::thread callable 的对象指针可以在线程开始执行后失效吗?

c++ - 这些有什么区别?

c - 指针 "char **strData"指向哪里?

c - 无法分配动态内存段错误

c++ - 果酱 SDK 模拟器错误 : Couldn't initialize Direct Draw

c++ - OpenCV,将一 block 像素从图像映射到图像时的噪声

c++ - 为什么模板只能在头文件中实现?

c++ - 帮助指针算术

c++ - 取消引用无效指针,然后获取结果的地址