对所有权使用unique_ptr,否则使用原始指针? [英] Use unique_ptr for ownership and raw pointer otherwise?

查看:64
本文介绍了对所有权使用unique_ptr,否则使用原始指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++ 11中编写一些代码。我有

I am C++11-ing some code. I have

class X { /* */ };

class A {
    std::vector<X*> va_x;
};

class B {
    std::vector<X*> vb_x;
    std::vector<A> vb_a;
};

类中 va_x的X *指向对象也指向B类中 vb_x的X * s。

The X*s of "va_x" inside my class A point to objects that are also pointed to by the X*s of "vb_x" inside my class B.

现在,我想使用智能指针。对我来说,显然B类拥有X *指向的对象的所有权(特别是因为我的A实例属于B)

Now I would like to use smart pointers. For me, it seems clear that class B has the ownership of the objects pointed by the X* (in particular because my A instances belong to B)

所以我应该使用B内部X的一个unique_ptr:

So I should use a unique_ptr for X inside B:

class B {
    std::vector<unique_ptr<X>> vb_x;
    std::vector<A> vb_a;
};

我的问题是,我应该为A类做什么?我应该保留原始指针吗?这样,在我的单元测试中,我必须承认它会导致尴尬的事情(imo),例如(不要担心封装,这不是重点):

My question is, what should I do for class A? Should I keep raw pointers? By doing so, in my unit tests, I must admit that it leads to awkward things (imo), for instance (don't worry about encapsulation, that's not the point):

unique_ptr<X> x(new X());
A a;
a.va_x.push_back(&(*x)); //awkward, but what else can I do?

A.vb_a.push_back(a); //ok
B.vb_x.push_back(move(x)); //ok


推荐答案

您可以使用 x.get(),它将返回内部指针。

You can use x.get(), which will return the internal pointer.

除此之外,是的,使用原始指针来处理非所有权参考是必经之路,另请参见此问题

Other than that, yes, using raw pointers to handle non-owning references is the way to go, see also this question.

这篇关于对所有权使用unique_ptr,否则使用原始指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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