如何在类中删除实例类
How to delete instance class inside class
考虑以下代码片段:
#include <iostream>
using namespace std;
class X {
public:
class Z {
public:
void f() {
cout << "Z().f()" << endl;
}
};
class Y {
public:
int A;
Y(int x) {
A = x;
}
int c() {
return A;
}
};
public:
Z* z;
// How to free Y instance ?
Y* a(int x) {
Y* y = new Y(x);
return y;
}
public:
X() {
z = new Z();
}
~X() {
delete z;
}
};
int main(void) {
int a;
X* x = new X();
cout << "input :" << endl;
cin >> a;
cout << "result : " << x->a(a)->c() << endl;
x->z->f();
delete x;
return 0;
}
虽然Z对象可以很容易地在~X()上释放,我很好奇如何释放Y一个?因为我没有分配任何变量来保存它的内存地址。
顺便说一下,这种东西的术语是什么?x -> c () () ->
谢谢。:)
// How to free Y instance ?
Y* a(int x) {
Y* y = new Y(x);
return y;
}
问题是,从函数原型来看,谁负责删除实例并不清楚。但是,由于只有调用方拥有实例的句柄,因此删除应该是被调用方的责任。这应该被很好的记录下来。但最好的方法是使用具有正确所有权语义的智能指针。在这种情况下,std::unique_ptr<Y>
似乎是一个合适的匹配,使用它的事实使意图明确,消除了有关所有权的文档的需要:
std::unique_ptr<Y> a(int x)
{
return std::unique_ptr<Y>( new Y(x) );
}
从函数返回内存,因此由调用者来删除它:
X x;
Y *ptr = x.a(5);
delete ptr;
希望你永远不会做这样的事情。如果你必须这样做,那么建议你使用智能指针,如shared_ptr
或unique_ptr
。
std::unique_ptr<Y> a(int x) {
return std::unique_ptr<Y>(new Y(x));
}
这样,就不必担心删除实例,因为指针类的析构函数承担了删除实例的责任。
相关文章:
- 从DLL中删除类的实例
- 删除功能不适用于串行通信后多个循环中的多个实例
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 使用部分模板实例化删除限定符
- 清除具有已删除赋值运算符的成员的类实例
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?
- 如何在C++中将类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- 是否可以实例化具有已删除构造函数和析构函数的非聚合类?
- 当指针指向的对象被另一个类的实例删除时,重新分配指针
- 如何创建一个结构的实例,当它不在范围内时,该实例将不会被删除
- 如何计算实例数组中未删除的实例
- 完全删除 QApplication 实例并在另一个线程中重新创建它
- 有条件地实例化具有删除默认构造函数的类
- 如何在返回一次数据后从类实例中删除数据
- 从字符串中删除字符的第一个和最后一个实例
- C++不允许堆栈实例,但允许新的删除
- 删除C++中动态分配的类实例
- 返回实例导致"尝试引用已删除的函数"错误
- 应由库或客户端代码删除已加载库中的对象实例
- 如何在类中删除实例类