C ++指针,对象等 [英] C++ Pointers, objects, etc

查看:234
本文介绍了C ++指针,对象等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有点混乱,但是...

It may be a bit confusing, but...

假设我在类中有一个向量类型成员,例如 vector< ;运算符*> (我在我的类中有方法从这个容器中返回运算符)。
现在让我说我有一个方法在我的类接收一个Operator对象 op 并将其插入向量。我想知道的是:我有任何麻烦,直接插入到向量( push_back(& op))?或者我应该使用复制构造函数创建一个新的操作符,然后将这个新的操作符放在向量上(使用push_back(new Operator(op)))?

Let's say I have a vector type member in a class, something like vector<Operator*> ( I have methods on my class to return Operators from this container). Now lets say that I have a method on my class that receives an Operator object op and inserts it on the vector. What I want to know is: will I have any trouble by insert it directly into the vector (push_back(&op))? Or should I use the copy constructor to create a new Operator and then put this new one on the vector (with push_back(new Operator(op)))?

是我创建的类)

推荐答案

好的,让我看看我是否遵循你的想法。
您已经创建了一个名为运营商的课程。
你有一个向量< Operator *> ,你想知道是否会有这个问题。

OK, let me see if I follow what you are trying to do. You've got a class you've created called Operator. You've got a vector <Operator *> and you're wondering if there will be issues with this.

简短的答案是肯定的,可能有。它是关于向量的范围,因为当它超出范围,分配在堆上的内存所有那些操作对象,你有指针在向量中的内存将不会被清除的向量。在非托管语言如c ++中,除非你使用一个专门的类来处理你的事情,你必须敏锐地意识到范围和潜在的内存泄漏。

Short answer is yes, there could be. It is about the scope of the vector because when it goes out of scope, the memory allocated on the heap for all those Operator objects that you've got pointers to in the vector will NOT be cleaned up by the vector. In an unmanaged language like c++, unless you are using a specialized class that takes care of things for you, you've got to be keenly aware of scoping and potential memory leaks.

两个问题你需要问自己:谁拥有Operator对象?和谁负责清理在堆上分配并由向量中的指针指向的 Operator 对象?

Two questions you need to ask yourself are "Who owns the Operator objects?" and "Who is responsible for cleaning up the Operator objects that were allocated on the heap and are pointed to by the pointers in the vector?"

您可以在拥有该向量的对象调用析构函数时自行清除该内存。

You can clean that memory up yourself when the destructor is called for the object that owns the vector.

我想您可能想查看类似的这个SO问题。还有其他解决方案 - 例如,使用boost类,可能会更好。

I think you might want to look at this SO question that is similar. There are other solutions - using boost classes, for instance, that might be better.

这篇关于C ++指针,对象等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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