gpt4 book ai didi

c++ - _ptr 或 _var - 哪个用作类字段,为什么?

转载 作者:太空狗 更新时间:2023-10-29 21:04:10 26 4
gpt4 key购买 nike

我有一个类:

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 有点困惑。我读过

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 是否合法?我根本不明白。

最佳答案

正如 Johnny 所指出的,这全都与内存所有权有关。如果将 _ptr 变量分配给 _var 变量,当 _var 变量超出范围时,内存将被删除,您最好不要使用该 _ptr 变量。

在您提供的情况下,当您调用 set 时,您将指针的所有权授予 Impl1 类型的对象。你仍然可以使用你拥有的那个,你可以调用 Impl1::get 但是因为你通过调用 set 给了那个 _ptr 的对象所有权,如果对象被删除所以执行该指针引用的内存。

关于c++ - _ptr 或 _var - 哪个用作类字段,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com