如何在指针中存储本地副本? [英] How to store a local copy inside a pointer?

查看:143
本文介绍了如何在指针中存储本地副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我执行以下操作:



If i do the following:

void addObject(myObject o, const int& i) {
    o.setI(i);

    this->myVector.push_back(&o);
}





我想o在函数结束时会被销毁。



因此,如何在myVector中安全地保存指针?

请注意,没有关于myVector存储指针而不是对象的争论。



I guess o gets destroyed at the end of the function.

Thus how, can I safely keep a pointer to it in myVector?
Note that, there's no arguing about myVector storing pointers and not objects.

推荐答案

使用此定义, o 是一个临时变量,其中包含传递给函数的对象的副本,而临时变量确实会在离开功能时被销毁。



根据您的需要,有两种可能的解决方案:



1.如果你可以保留对现有对象的引用,你需要做的就是通过引用传递对象,而不是通过值:

Using this definition, o is a temporary variable holding a copy of the object passed to the function, and that temporary will indeed be destroyed upon leaving the function.

There are two possible solutions, depending on what you want:

1. If you're ok to just keep a reference to an existing object, all you need to do is pass the object by reference, rather than by value:
void addObject(myObject& o, const int& i) {



在这种情况下, o 是一个参考,& o 是一个指针传递给函数的对象。



2.如果你想要一个幸存在函数范围内的原始对象的副本,你需要创建一个副本堆,而不是堆栈。请注意,在这种情况下,您还应该通过引用传递原始对象 - 这次只需将其设为 const 引用:


In this case, o is a reference, and &o is a pointer to the object passed to the function.

2. If you want a copy of the original object that survives the scope of the function, you need to create the copy on the heap, rather than the stack. Note that in this case you also should pass the original object by reference - just make it a const reference this time:

void addObject(const myObject& o, const int& i) {
   myObject* po = new myObject(o); // call copy constructor
   po->set(i);
   this->myVector.push_back(po);
}


这篇关于如何在指针中存储本地副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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