我有一个std::list的Entity对象(屏幕上的对象).在一个类中EntityContainer,我有一个指向不同实体的指针列表.当a EntityContainer被破坏时,我希望该列表中的所有实体也被破坏.我怎么能这样做,同时避免导致删除列表成员的迭代器错误?
EntityContainer::~EntityContainer()
{
// Destroy children
int numChildren = children.size();
for (int i = 0; i < numChildren; i++)
{
Entity*& child = children.back();
delete child;
}
}
Run Code Online (Sandbox Code Playgroud)
上面导致std :: list :: clear()中的空指针访问冲突,它在销毁期间被调用EntityContainer,因为它是该对象的成员变量.我相信这是因为我删除了列表中的对象,所以当然删除它们时会尝试访问它们.但是,我的问题是,如果我只是保留它,并允许列表clear()而不显式删除其中的对象,则永远不会调用它们的析构函数.我只能假设这是因为列表只破坏列表中的指针,而不是指针指向的对象.这主要是作为假设 - 我可能是错的.你会怎么做?
以下代码给出了错误:
void EntityContainer::AddChild(Entity* child)
{
unique_ptr<Entity> childPtr(child);
children.push_back(childPtr);
}
Run Code Online (Sandbox Code Playgroud)
我认为这可能不是为现有对象创建unique_ptr的正确方法.怎么能这样做呢?上面的代码给出了以下错误:
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(617): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
Run Code Online (Sandbox Code Playgroud) 尝试在结构中将函数指针分配给函数指针时遇到问题。
我有一个struct command,它包含一个调用字符串值,一条消息以确认其激活以及一个在激活时要调用的函数。
但是,我在下面的结构的构造函数中分配函数指针时遇到麻烦(可能稍后将结构变成一个类,不确定)。
struct Command
{
Command(string _code, string _message, void *_func(void))
: code(_code), message(_message) { /* ERROR: */ func = _func; }
string code; // The string that invokes a console response
string message; // The response that is printed to acknowledge its activation
void *func(void); // The function that is run when the string is called
};
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,标/* ERROR: */有的错误出现了"expression must be a modifiable value"。我怎样才能解决这个问题?我只想将对函数的引用传递给该结构。