_ptr或_var - 哪一个用作类字段,为什么? [英] _ptr or _var - which one use as a class field and why?

查看:229
本文介绍了_ptr或_var - 哪一个用作类字段,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类:

class Impl1 : public POA_I1
{
   private :
          Impl2_var ob;
   public :
          Impl2_ptr get();
          {
             return ob;
          }

          void set(::Impl2_ptr ob)
          {
             this->ob = ob;
          }
};

我是一个关于 _ptr _var 。我读了这个

I'm a litte bit confused about _ptr and _var. I read that


MyObject_var对象引用类型的_var版本作为一个
句柄toproxy, _ptr引用,但也添加
内存管理。像所有_var类型一样,当引用超出范围时,_var引用负责释放
释放其底层实例(在这种情况下,代理
实例)。 _ptr引用
和_var引用允许客户端访问操作onproxy
实例

MyObject_var The _var version of the object reference type acts as a handle toproxy in much the same way as a _ptr reference but also adds memory management. Like all _var types, a _var reference takes care of deallocating its underlying instance (in this case, the proxy instance) when the reference goes out of scope. Both _ptr references and _var references allow the client to access operations onproxy instance

不明白什么时候使用每一个,为什么。我的意思是,在我的实现=我应该使用, _var _ptr 为什么?在类中有一个类型 _var 的字段是否合法,并在setter中返回 _ptr

but I dont understand when to use each one and why. I mean, in my implementation = which one should I use, _var or _ptr and why? And is it legal to have a field of type _var in class and return _ptr in setter? I just don't get it at all.

推荐答案

正如Johnny指出的,这完全是关于内存所有权。如果将_ptr变量赋值给_var变量,当_var变量超出范围时,内存将被删除,最好不要使用_ptr变量。

As Johnny pointed out, it's all about memory ownership. If you assign an _ptr variable to an _var variable, when the _var variable goes out of scope the memory will be deleted and you better not use that _ptr variable.

当您调用 set 时,您将提供类型 Impl1 指针所有权的对象。你仍然可以使用你所拥有的,你可以调用 Impl1 :: get ,但因为你通过调用 set ,如果对象被删除,那么该指针引用的内存。

In the case you provided, when you call set you are giving an object of type Impl1 ownership of the pointer. You can still use the one you have, you can call Impl1::get but since you gave the object ownership of that _ptr by calling set, if the object gets deleted so does the memory referenced by that pointer.

这篇关于_ptr或_var - 哪一个用作类字段,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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