C++ C++;存储在向量中的自由指针
因此,我有这些功能(C++ C++;存储在向量中的自由指针,c++,pointers,vector,runtime-error,delete-operator,C++,Pointers,Vector,Runtime Error,Delete Operator,因此,我有这些功能(Game继承自GameInterface;它们目前都没有任何用途,我只是在测试我的想法是否可以实现。): 使用智能指针,但当我执行程序时,总是会得到相同的调试断言错误:_BLOCK_TYPE_是有效的(pHead->nBlockUse) 你知道问题出在哪里吗?谢谢 编辑: 好的,我有类游戏:虚拟公共游戏界面。删除了virtual关键字,现在可以正常工作了。但我不知道为什么(我甚至不知道他虚拟关键词做了什么;我主要是在测试东西,因为我对这门语言有点陌生,所以请耐心听我说) 编辑
Game
继承自GameInterface
;它们目前都没有任何用途,我只是在测试我的想法是否可以实现。):
使用智能指针,但当我执行程序时,总是会得到相同的调试断言错误:_BLOCK_TYPE_是有效的(pHead->nBlockUse)
你知道问题出在哪里吗?谢谢
编辑:
好的,我有类游戏:虚拟公共游戏界面
。删除了virtual
关键字,现在可以正常工作了。但我不知道为什么(我甚至不知道他虚拟关键词做了什么;我主要是在测试东西,因为我对这门语言有点陌生,所以请耐心听我说)
编辑2:
强制
GameInterface
析构函数为虚拟的似乎是正确的解决方案。以下代码应该大致正确:
#include <memory>
#include <vector>
struct GameInterface
{
virtual ~GameInterface() {}
virtual std::vector<std::unique_ptr<GameInterface>> generateChildren() = 0;
};
struct Game : GameInterface
{
std::vector<std::unique_ptr<GameInterface>> generateChildren() override
{
std::vector<std::unique_ptr<GameInterface>> result;
for (int i = 0; i != 10; ++i)
{
result.emplace_back(new Game(result.empty()
? *this
: *result.back()));
++result.back()->npawns;
}
return result;
}
};
int getBestMovement(GameInterface* gf)
{
auto v = gf->generateChildren();
// ...
return 0;
}
#包括
#包括
结构游戏界面
{
虚拟~GameInterface(){}
虚拟std::vector generateChildren()=0;
};
结构游戏:游戏界面
{
std::vector generateChildren()重写
{
std::向量结果;
对于(int i=0;i!=10;++i)
{
result.emplace_back(新游戏(result.empty)()
?*这个
:*result.back());
++result.back()->npawns;
}
返回结果;
}
};
int getBestMovement(游戏界面*gf)
{
自动v=gf->generateChildren();
// ...
返回0;
}
如何定义Game::Game(const-Game&)
呢?我建议改为使用类似std::vector
的工具,这样可以正确管理内存。如果使用智能指针,你真的应该到处使用智能指针。确保任何代码的任何部分都没有被传递到普通的GameInterface*
。Game::~Game()
实现的源代码也会很有用默认的复制构造函数工作得很好(Game
只有整数npawns
,输出是我们期望的)。新游戏(*此)
具有与原始代码不同的行为
const int Library::getBestMovement(GameInterface* gf) const {
vector<GameInterface*> vgf = gf->generateChildren();
int nchildren = vgf.size();
// outputs "child #i has (i+1) pawns" for i in 0..9
for (int i = 0; i < nchildren; ++i) {
cout << "child #" << i << " has " << vgf[i]->num_of_pawns() << " pawns" << endl;
}
// missing some dynamic memory management (deleting the pointers in vgf)
return 0;
}
for (auto it = vgf.begin(); it != vgf.end(); ++it)
delete *it;
#include <memory>
#include <vector>
struct GameInterface
{
virtual ~GameInterface() {}
virtual std::vector<std::unique_ptr<GameInterface>> generateChildren() = 0;
};
struct Game : GameInterface
{
std::vector<std::unique_ptr<GameInterface>> generateChildren() override
{
std::vector<std::unique_ptr<GameInterface>> result;
for (int i = 0; i != 10; ++i)
{
result.emplace_back(new Game(result.empty()
? *this
: *result.back()));
++result.back()->npawns;
}
return result;
}
};
int getBestMovement(GameInterface* gf)
{
auto v = gf->generateChildren();
// ...
return 0;
}