将子对象指针更改为父指针(无内存泄漏) [英] Changing child object pointer to parent pointer (without memory leak)

查看:93
本文介绍了将子对象指针更改为父指针(无内存泄漏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此问题中:条件对C ++中的多态对象有什么作用? (包含多态性)

我遇到这样的情况:父指针指向由前面的条件语句确定的两个可能对象之一。这是代码:(与解决方案一起重新发布)

I have a situation where a parent pointer is pointing at one of two possible objects determined by the preceding conditional statement. Here is the code: (Reposted with solution)

ClassParent *parentPointer; //Declare pointer to parent

if (condition) {
    ClassChild1* mychild = new mychild1(); //Initialize ClassChild1 object with pointer mychild
    parentPointer = mychild;//Parent pointer points to child1
}

if (!condition) {
    ClassChild2* mychild = new mychild2(); //Initialize ClassChild1 object with pointer mychild
    parentPointer = mychild;//Parent pointer points to child2  
}

cout << *parentPointer;

问题是,我的对象是使用mychild指针创建的,但我希望该指针是临时的。一旦对象由parentPointer指向,我要确保删除mychild指针(只是指针而不是对象)。

The problem is, my object is created with mychild pointer but I want this pointer to be temporary. Once the object is pointed to by the parentPointer, I want to make sure mychild pointer is deleted (just the pointer not the object).

我不确定当指针超出范围时将发生,因为指针是在 new的上下文中声明的。

I'm not sure if this will happen when it goes out of scope, because the pointer was declared within the context of 'new'.

我需要手动删除mychild指针吗?如果是这样,如何删除指针而又不导致parentPointer超出范围?

Do I need to delete the mychild pointer manually? If so, how do I delete the pointer without causing the parentPointer to go out of bounds?

推荐答案

请考虑以下代码。 / p>

Consider the following code.

#include <iostream>

using namespace std;

class A { };

class B: public A { };

class C: public A { };

ostream &operator<<(ostream &os, const A &){ return os << 'A'; }

ostream &operator<<(ostream &os, const B &){ return os << 'B'; }

ostream &operator<<(ostream &os, const C &){ return os << 'C'; }

int main(){
    A *a1=new B;
    A *a2=new C;
    cout << *a1 << *a2 << '\n';
}

它将打印 AA ,而不是 BC 。即使指针 a1 a2 确实指向类型为 B C ,它们的类型仍然是指向 A 的指针,并且当您应用 * 运算符,表达式的类型为 A

It will print AA, not BC. Even though the pointers a1 and a2 really point to objects of types B and C, they're still of type "pointer to A", and when you apply the * operator to them, the expression will have the type A.

要真正行使对象的多态性,应该使用虚函数。

To really exercise object polymorphism, you should use virtual functions.

class A {
    public:
        virtual char getName() const { return 'A'; }
};

class B {
    public:
        char getName() const { return 'B'; }
};

class C {
    public:
        char getName() const { return 'C'; }
};

ostream &operator<<(ostream &os, const A &a_like){
    return os << a_like.getName();
}

// remove ostream &operator<<(ostream &os, const B &)

// remove ostream &operator<<(ostream &os, const C &)

编辑:最后,由于您提到了不存在内存泄漏,而且还将指向派生类型的对象的指针存储在基本类型的指针的集合中,因此您可能希望将析构函数设为虚拟的也是。这样,在销毁指针时释放的资源(通过 delete 运算符)或对基本类型的引用将对实际基础执行必要的清理操作。

Lastly, since you mentioned not having memory leaks and also storing pointers to objects of derived types in a collection of pointers to the base type, you'll probably want to make your destructors virtual as well. By doing so, the resources freed at the destruction of the pointer (through the delete operator) or reference to the base type will perform the necessary clean-up actions on the actual underlying object of the derived type.

也不要忘记,如果您有类似 vector< SomeClass *> ,则在向量容器销毁时,不会单独删除指针元素 d。在销毁向量之前,您应该显式地删除每个元素,并用智能指针(例如 unique_ptr )包围指针或 shared_ptr ),或为多态对象创建自己的RAII信封,也许知道移动操作。

Don't forget, also, that if you have something like vector<SomeClass *>, the pointer elements will not be individually deleted at the time of destruction of the vector container. You should either explicitly delete each element before the vector gets destroyed, envelop your pointers with a smart pointer (such as unique_ptr or shared_ptr), or create your own RAII envelope to your polymorphic objects, perhaps aware of with move operations.

这篇关于将子对象指针更改为父指针(无内存泄漏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆