gpt4 book ai didi

c++ - 删除传递给构造函数的对象指针导致错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:59 25 4
gpt4 key购买 nike

我是 C++ 的新手,所以我正在尝试借助维基百科的示例来学习它。我玩了一些类(class),但遇到了段错误。

这是我的代码:

class SomeClass {};

class AnotherClass {
SomeClass* sc
public:
AnotherClass(SomeClass* SC):( sc = SC; ){}

//***********************************************************************
~AnotherClass(){ delete sc; } //here I'm getting rid of internal pointer
//***********************************************************************
};

int main( int argc, char* argv[] ) {
SomeClass* SC = new SomeClass();
AnotherClass* AC = new AnotherClass(SC);

delete AC;

// *****************************************************
delete SC; //i think that this line might cause an error
//******************************************************

return 0;
}

我想,我应该删除每个指针来释放堆内存?!能否请您指出我的错误。

编辑:

这是我的真实代码:

#include <iostream>
#include <string>

using namespace std;

class Pizza {
string dough;
public:
Pizza(string d):dough(d) {}
void setDough( string value ) { dough = value; }
string getDough() { return dough; }
};

class PizzaBuilder {
Pizza* pizza;

public:
PizzaBuilder( Pizza* p ) { pizza = p; }
~PizzaBuilder() { delete pizza; cout << "PizzaBuilder Destructor." << endl;}

PizzaBuilder* addExtra(string extra) {
string special = pizza->getDough() + " and extra " + extra;
pizza->setDough(special);
return this;
}
Pizza* getPizza() { return pizza; }
};

int main(int argc, char* argv[]) {

Pizza* p = new Pizza("My Special DOVE!");
PizzaBuilder* pb = new PizzaBuilder(p);

pb->addExtra("Mushrooms")->addExtra("Anchovies")->addExtra("Zefir")->addExtra("Chilli");

cout << p->getDough() << endl;

delete pb;
delete p;

return 0;
}

最佳答案

delete 并不像您想象的那样删除指针。它删除指针指向的对象。因此,您要删除 SC 指向的对象两次:一次来自 main,另一次来自 AC 指向的对象的析构函数,当删除它。

并且多次删除一个对象是未定义的行为。

关于c++ - 删除传递给构造函数的对象指针导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com