简体   繁体   English

破坏 null 指针时的访问冲突

[英]Access violation on destruction of a null pointer

The problem I am having is that when my class CLimb runs its destructor, if member *parent is NULL I get an "Access violation writing location 0xcccccccc" error, after the destructor is called, but before the body is executed.我遇到的问题是,当我的 class CLimb 运行其析构函数时,如果成员*parentNULL ,我在调用析构函数之后但在执行主体之前收到“访问冲突写入位置 0xcccccccc”错误。

limb.h肢体.h

class CLimb
{
public:
    CLimb(void);
    CLimb(CLimb *_parent);
    ~CLimb(void);

    float cut;
    float bone;
    float resistance;

    CLimb *parent;
};

limb.cpp肢体.cpp

#include "limb.h"


CLimb::CLimb(void) :
    cut(0),
    bone(0),
    resistance(0)
{
    parent = NULL;
}

CLimb::CLimb(CLimb *_parent) :
    cut(0),
    bone(0),
    resistance(0)
{
    parent = _parent;
}

CLimb::~CLimb(void)
{
}

I was also wondering if I had 2 instances, limb01 and limb02 , where limb02 is the parent of limb01 , if limb02 is deleted limb01->parent now points to an incorrect address.我还想知道我是否有两个实例, limb01limb02 ,其中limb02是limb01 的父limb01 ,如果limb02被删除, limb01->parent现在指向一个不正确的地址。 How would I resolve this?我将如何解决这个问题? Would I have to add a *child pointer as well?我还必须添加一个*child指针吗?

Smart pointers are a solution.智能指针是一种解决方案。 In particular, you can use a weak pointer here.特别是,您可以在此处使用弱指针。 A weak pointer is automatically reset when the reference count of the pointed-to object drops to zero (ie when it's deleted).当指向的 object 的引用计数降至零(即,当它被删除时)时,弱指针会自动重置。

I assume your problem is that you are accessing the pointer after deleting it.我假设您的问题是您在删除指针后正在访问它。 So you need to keep track of which pointers point to valid objects, and which to dead ones.因此,您需要跟踪哪些指针指向有效对象,哪些指向死对象。

There are several ways to resolve such problems more or less automatically.有几种方法可以或多或少地自动解决此类问题。

A popular one would be using some kind of smart pointers, for example, shared_ptr .一种流行的方法是使用某种智能指针,例如shared_ptr This would ensure that an object won't be deleted if there are still references to it.这将确保 object 在仍有引用时不会被删除。

Another approach is to establish a hierarchy: make each parent control the lifetime of its children.另一种方法是建立层次结构:让每个父级控制其子级的生命周期。 This means that (1) the children need to be deleted in the parent's destructor, and (2) no one except the parent should keep a pointer to a child (at least, for a long time).这意味着(1)需要在父级的析构函数中删除子级,以及(2)除了父级之外,没有人应该保留指向子级的指针(至少,很长一段时间)。

Yet another popular approach would be using garbage collection, but I wouldn't recommend it in non-managed environments.另一种流行的方法是使用垃圾收集,但我不建议在非托管环境中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM