继续我的 previous question ,我想请教以下问题:
给定一个 C++ 函数,其中有一个 new 语句但没有显式返回任何内容(即使用 return 语句),它是否也应该始终有一个 delete?
如果不是,能否请您举个例子。
最佳答案
它不必显式返回新创建的对象,但它应该以某种方式将其传递给其他对象。可能的场景包括:
- 在成员函数中,创建一个对象并将其分配给包含对象的字段。
例子:
class Foo {
private:
Baz* baz;
public:
Foo() : baz(0) { }
void create_bar() { baz = new Baz(); }
~Foo() { delete baz; }
};
- 将新对象传递给其他对象。
例子:
void foo() {
// assuming bar lives in the global scope
bar.baz = new Baz();
}
void foo2(Bar& bar) {
bar.baz = new Baz();
// or, better:
bar.setBaz(new Baz());
}
- 使用某种垃圾收集指针类型。
例子:
std::auto_ptr<Baz> foo() {
return new Baz();
}
- 将指针传递给另一个函数,该函数对其进行处理,然后将其删除。
例子:
void foo(Bar* bar) {
bar->dostuff();
delete bar;
}
void baz() {
Bar* bar = new Bar();
foo(bar);
}
关于c++ - 顺序新建和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6745480/