C++指针、对象等

发布于 2024-08-29 08:56:19 字数 320 浏览 7 评论 0原文

这可能有点令人困惑,但是......

假设我在一个类中有一个向量类型成员,类似于 vector (我的类上有方法可以从中返回运算符容器)。 现在假设我的类中有一个方法,该方法接收 Operator 对象 op 并将其插入到向量上。我想知道的是:直接将其插入向量(push_back(&op))会有什么麻烦吗?或者我应该使用复制构造函数创建一个新的运算符,然后将这个新的运算符放在向量上(使用push_back(new Operator(op)))?

(Operator是我创建的一个类)

It may be a bit confusing, but...

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 is a class I created)

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

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

发布评论

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

评论(2

月竹挽风 2024-09-05 08:56:19

使用 &op 仅提供指向对象的指针(仍在堆栈上),而不是副本。因此,当对象超出范围(并被清理)时,向量中的指针将变得无效并会导致问题。

最好的选择是使用上面建议的复制构造函数。

Using &op only gives you a pointer to the object (which is still on the stack) and not a copy. Thus when the object goes out of scope (and gets cleaned up) the pointer in the vector becomes invalid and will cause issues.

Your best bet is to use the copy constructor as you suggested above.

风筝有风,海豚有海 2024-09-05 08:56:19

好吧,让我看看我是否遵循你想要做的事情。
您创建了一个名为 Operator 的类。
您有一个向量并且您想知道这是否会出现问题。

简短的回答是肯定的,可能有。它与向量的范围有关,因为当它超出范围时,在堆上为向量中指向的所有运算符对象分配的内存将不会被向量清理。在像 c++ 这样的非托管语言中,除非您使用专门的类来为您处理事务,否则您必须敏锐地意识到作用域和潜在的内存泄漏。

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

当为拥有该向量的对象调用析构函数时,您可以自己清理该内存。

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

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.

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.

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.

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.

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