我如何*不*删除析构函数中的成员?

发布于 2024-07-26 10:00:20 字数 129 浏览 9 评论 0原文

我希望我的类的析构函数删除整个对象,但其中一个成员除外,该成员在其他地方被删除。 首先,这是不是完全不合理? 假设不是,我该怎么做? 我认为创建一个空主体的析构函数会阻止所有成员被删除(因为析构函数不会执行任何操作),但情况似乎并非如此。

I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because the destructor wouldn't do anything), but that doesn't seem to be the case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

巴黎盛开的樱花 2024-08-02 10:00:21

首先,如果成员对象是按值包含的,那么当容器对象被销毁时,它就会超出范围,并且您无法阻止它被自动释放。

相反,如果它是由容器对象间接引用的(例如使用指针),则您不必执行任何操作来删除它。 除非您明确编写代码来执行此操作,否则析构函数不会删除任何内容。

至于这是否不合理的问题,我认为一般来说不是,但是你必须明确(通常在文档中,因为C++没有对这个概念的语言支持)拥有< /strong> 有问题的成员。

First of all, if the member object is contained by value, it simply goes out of scope when the container object is destroyed, and you cannot prevent it from being deallocated automatically.

If, instead, it is indirectly referenced by your container object (for example with a pointer), you don't have to do anything in particular to not delete it. The destructor doesn't delete anything unless you explicitly write the code to do so.

As for the question whether this is unreasonable, I think it is not, in general, but you have to make clear (usually in the documentation, since C++ has no language support for this concept) what is the object that owns the member in question.

困倦 2024-08-02 10:00:21

我认为在大多数情况下,如果您不在同一操作中破坏整个对象,那么您就是在自找麻烦。 听起来你的类应该有一个针对该成员的清理方法,该方法在析构函数中调用。 如果由于某种原因必须提前销毁该成员,则该方法可以提前返回。

I think that in most cases you're asking for trouble if you don't destruct the entire object in the same action. It sounds like your class should have a clean up method for that member, which is called within the destructor. If for some reason the member has to be destroyed sooner, the method can return early.

撩心不撩汉 2024-08-02 10:00:21

首先,这完全是吗?
不合理吗?

我不会说不合理,也许值得怀疑。

对于一个类来说,拥有它是完全有效的,因此应该负责清理,同时在另一个类中拥有指向该对象的引用或指针。

但是,第二个类是否真的应该具有该指针可能是有问题的,我更愿意在需要时始终使用 get 方法来检索该指针,例如通过调用父类或某些资源管理器。

First of all, is this totally
unreasonable?

I wouldn't say unreasonable, perhaps questionable.

It's perfectly valid for one class to own and therefore should take care of clean up, while at the same time having a reference or a pointer to that object in another class.

However, it might be questionable if the second class reall should have that pointer or not, I'd prefer to always use a get-method to retrieve that pointer whenever I need it, e.g. by calling a parent class or some resource manager.

不回头走下去 2024-08-02 10:00:21

如果您为此成员动态分配了内存,则在销毁对象之前共享对此成员的引用并且确保该成员不会在对象的析构函数中销毁时,这是可能的。 但我认为这种做法不太合理。

If you have dynamically allocated memory for this member it is possible once you have shared the reference to this member before destroying the object and if you ensure the member is not destroyed in the object's destructor. However I think this practice isn't so reasonable.

a√萤火虫的光℡ 2024-08-02 10:00:21

当您谈论在析构函数中删除类成员时,您必须区分非指针成员和非指针成员。 假设您有一个这样的类:


class Foo
{
public:
  Foo() {p = new int;}
 ~Foo(){}

private:
 int a;
 int *p;
};

该类有 2 个数据成员:一个整数 a 和一个指向整数 p 的指针。 当析构函数被调用时,对象被销毁,这意味着它的所有成员的析构函数都被调用。 即使析构函数的主体为空,也会发生这种情况。 对于基本类型(如整数),调用其析构函数仅意味着其占用的内存将被释放。 但是,当您销毁指针时,有一个问题:默认情况下,它指向的任何内容都不会被销毁。 为此,您必须显式调用delete

因此,在我们的示例中,当调用析构函数时,a 将被销毁,p 也会被销毁,但 p 所指向的任何内容都不会被销毁。 如果您希望释放 p 指向的内存,Foo 的析构函数应如下所示:


~Foo() {delete p};

因此,回到您的问题,当调用对象的析构函数时,无论如何,类中所有不是指针的成员都将被销毁。 另一方面,如果您有指针成员,则它们指向的任何内容都不会被销毁,除非您在析构函数中专门为它们调用删除。

When you talk about class members being deleted in the destructor, you have to make a distinction between members that are not pointers and those that are. Let's say you have a class like this:


class Foo
{
public:
  Foo() {p = new int;}
 ~Foo(){}

private:
 int a;
 int *p;
};

This class has 2 data members: an integer a and a pointer to an integer p. When the destructor is called, the object is destroyed, meaning that the destructors for all its members are called. This happens even if the destructor's body is empty. In the case of a primitive type, like an integer, calling its destructor just means that the memory it occupies will be released. However, there is a catch when you destroy a pointer: whatever it points to does not get destroyed by default. For that you have to explicitly call delete.

So in our example, a will be destroyed when the destructor is called, and so will p, but not whatever p points to. If you wish to free the memory to which p points, the destructor for Foo should look like this:


~Foo() {delete p};

So, getting back to your question, all the members of your class which are not pointers will be destroyed no matter what, when the object's destructor is called. On the other hand, if you have members that are pointers, whatever they point to will not be destroyed, unless you specifically call delete for them in the destructor.

夜还是长夜 2024-08-02 10:00:21

怎么没人提到弱指针和强指针?
强指针是正常行为的智能指针。
弱指针是一种智能指针,除非所有强指针都超出范围,否则无法删除自身。
强指针表示所有权,弱指针表示共享。
查看 boost.shared_ptrboost.weak_ptrLoki 的 StrongPtr 实现。
另请查看 RAII。 如果您了解 RAII,您自己就会知道这个问题的答案。

How come no one mentioned weak and strong pointers?
A strong pointer is a smart pointer that acts normally.
A weak pointer is a smart pointer that cannot delete itself unless all of the strong pointers are out of scope.
Strong pointer indicates ownership, a weak pointer indicates sharing.
Look at boost.shared_ptr and boost.weak_ptr and Loki's StrongPtr for implementations.
Also take a look at RAII. If you knew RAII you would have known the answer to this question yourself.

北凤男飞 2024-08-02 10:00:21

这并非不合理,但应注意确保隐式处理任何托管资源的清理。

(人们通常担心的第一个托管资源是内存,但是任何可能泄漏的东西——内存、文件句柄、IDispatch 指针——都应该有隐式处理清理的代码)。

对于多个对象共享的托管资源(几乎肯定是这种情况,如果“这个对象”应该有一个指向“那个对象”清理的东西的指针),您通常需要一个“引用计数指针”来管理对象或“弱指针”,具体取决于您的生命周期要求。

对于不共享的托管资源(特别是那些在可能引发异常时需要正确管理的资源),auto_ptr 或其他变体可能更合适。

Scott Meyers 的《Effective C++》书籍是学习智能指针的合理起点,但在实践中,您可能应该使用经过审查的库,例如 Boost 让其他人担心一些晦涩的极端情况(比如如果构造函数抛出异常会发生什么?)。

It is not unreasonable, but care should be taken to ensure that cleanup of any managed resources is handled implicitly.

(The first managed resource that people generally worry about is memory, but anything that can leak - memory, file handles, IDispatch pointers - should have code which handles the cleanup implicitly).

For managed resources shared by multiple objects (almost certainly the case if "this object" is supposed to have a pointer to something that gets cleaned up by "that object"), you are normally needing either a "reference counted pointer" to manage the object or a "weak pointer", depending on your lifetime requirements.

For managed resources which are not shared (and in particular those that need to be managed properly when exceptions can be thrown), then an auto_ptr or other variant may be more suitable.

The Scott Meyers Effective C++ books were a reasonable starting point for learning about smart pointers, but in practice you should probably just grab a vetted library like Boost and let somebody else worry about getting the obscure corner cases (like what happens if a constructor throws an exception?) right.

━╋う一瞬間旳綻放 2024-08-02 10:00:21

这是可能的,但基本上正如 @dmckee 所说,这是一个所有权问题。 如果是这种情况,您可以重新计票。 IE

class A
{

RefObj* obj;
A()
{

obj = new RefObj;

}

~A()
{
 obj->ReleaseRef();
}
}


RefObj
{

int m_iRefCounter;
RefObj()
{
m_iRefCounter = 1;
}
AddRef()
{
m_iRefCounter++;
}
ReleaseRef()
{
m_iRefCounter--
if(m_iRefCounter == 0)
{
 delete this;
}
}
}

}

This is possible but basically as @dmckee said it is then a ownership issue. If that is the case may be you can go for refcounting. i.e.

class A
{

RefObj* obj;
A()
{

obj = new RefObj;

}

~A()
{
 obj->ReleaseRef();
}
}


RefObj
{

int m_iRefCounter;
RefObj()
{
m_iRefCounter = 1;
}
AddRef()
{
m_iRefCounter++;
}
ReleaseRef()
{
m_iRefCounter--
if(m_iRefCounter == 0)
{
 delete this;
}
}
}

}

把梦留给海 2024-08-02 10:00:20

简短回答:你不知​​道。

更长的答案:如果“成员”实际上是指向其他分配的指针,您可以安排不删除其他分配。

但通常,如果您在构造函数中分配了另一个块,则需要在析构函数中将其删除。 其他任何事情都需要仔细处理相关区块的“所有权”。 这很像普通 c 中的内存管理。 有可能,但充满危险。

祝你好运。

Short answer: You don't.

Longer answer: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation.

But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "ownership" of the block in question. It will be a lot like memory management in plain c. Possible, but fraught with danger.

Good luck.

或十年 2024-08-02 10:00:20

取决于你所说的“删除”是什么意思。 如果它们不在智能指针中,并且没有显式删除,那么它们就不会被删除。 只是类的一部分的成员:

class Bar {
//...
private: 
  Foo foo;
};

不会被析构函数删除(因为它们不是动态分配的),它们只是被销毁。 他们“生活”在班级内部,所以一旦班级被破坏,班级就消失了。

如果您正在寻找两个位置之间的共享“所有权”,您需要的是动态分配的shared_ptr:

#include <memory>
class Bar {
// ...
private:
  std::tr1::shared_ptr<Foo> foo;
};

Depends on what you mean by "deleted". If they aren't in a smart pointer, and aren't explicitly deleted, then they aren't deleted. Members that are just part of the class:

class Bar {
//...
private: 
  Foo foo;
};

Aren't deleted by the destructor (because they weren't dynamically allocated), they are just destroyed. They "live" inside the class, so once it is destroyed, it's gone.

If you are looking the share "ownership" between two locations, what you want is a dynamically allocated shared_ptr:

#include <memory>
class Bar {
// ...
private:
  std::tr1::shared_ptr<Foo> foo;
};
日记撕了你也走了 2024-08-02 10:00:20

如果该成员包含在中(不是通过指针或引用),那么您无法阻止它被删除,而且您也不应该这样做。

如果您想在其他地方删除它,则将其包含在指针或引用中。

class House
{
  Door door; //contained by value, will be destroyed when the House is
}

class House
{
  Door& door; //contained by reference, will not be destroyed when the House is
}

If the member is contained by value (not by pointer or by reference) then you can't prevent it from being deleted and you shouldn't want to.

If you want to delete it elsewhere instead, then make it contained by pointer or by reference.

class House
{
  Door door; //contained by value, will be destroyed when the House is
}

class House
{
  Door& door; //contained by reference, will not be destroyed when the House is
}
笑饮青盏花 2024-08-02 10:00:20

析构函数中的代码只是删除动态分配的成员。 成员的销毁不是可选的,您只能控制之前显式分配的内容的释放(使用operator new)。

您想要做的事情可以使用shared_ptr来获得,其中您的类和外部代码共享一个指向同一外部对象的指针。 这样,只有当所有指向该对象的指针超出范围时,它才会被删除。 但要注意不要做循环引用,shared_ptr 没有“垃圾收集器”智慧。

当然,您可以使用这些地方共享的常规指针,但在大多数情况下这不是一个好主意,很容易让您在以后对正确的资源释放感到头痛。

The code in the destructor is only to delete members that are dynamically allocated. The destruction of members is not optional, you can only control the deallocation of what you explicitly allocated before (with operator new).

What you want to do can be obtained using a shared_ptr, in which both your class and the external code share a pointer to the same external object. This way, only when all the pointers to that object go out of scope it will be deleted. But beware not to do circular references, shared_ptr has no "garbage collector" wisdom.

Of course you could use a regular pointer shared by those places, but this is in most cases a bad idea, prone to give you headaches about proper resource deallocation later.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文