所以我遇到了家庭作业的问题 - 因为getApple
是 const,我无法设置locallyAllocated = false
,这意味着每当getApple
在其他程序中实例化并释放苹果时,我的析构函数都会尝试释放内存并抛出一个 double免费错误。我做错了什么,我该如何解决?注意:函数,它们的参数和签名必须是我们分配的方式。非常感谢!
class poop
{
Apple localApple;
bool locallyAllocated;
void* pointer;
public:
poop(const Apple &apple)
{
//Set our local apple to the apple in the provided address
localApple = apple;
locallyAllocated = false;
}
poop(string descr)
{
localApple.description = descr;
pointer = maloc(sizeof(localApple);
localApple.pointer = pointer
locallyAllocated = true;
}
~poop()
{
if(locallyAllocated)
{
//This throws a double free error if "getApple" is ever called
free(pointer);
}
}
void getApple(Apple* apple) const
{
if(apple)
{
//Copies our local apple into the address of the given apple
//Because this function is "const", i can't do anything like set "locallyAllocated" to false
*apple = localApple
}
}
}