如何初始化一个 class 成员的智能指针?

How do I initialize a smart pointer which is a class member?

对 C++ 相当陌生,所以这可能是一个非常愚蠢的问题。我需要 cube_normals 指针被成员函数 read_models()proc_models() 访问,并且每次调用 read_models() 时都必须初始化指针。

在成员函数中我可以做的:

PointCloud<A>::Ptr cube_normals (new PointCloud<A>);

我可以将指针传递给其他函数,但我正在使用 12 个这样的指针,这可能不是解决此问题的最简洁方法。

这是代码片段。提前致谢!

class preproc
{

public:

    preproc();
    ~preproc();
    PointCloud<A>::Ptr cube_normals;

    void read_models();
    void proc_models();

private:

    ros::NodeHandle nh;
    ros::NodeHandle nh_priv;
};

问题

如果在成员函数中有这样的语句:

PointCloud<A>::Ptr cube_normals (new PointCloud<A>);

您将创建一个局部变量 cube_normals,它将隐藏同名的 class 成员。

解决方法

如果目标是每次调用 read_models() 时创建一个新的空对象,您可以选择赋值。

问题是以下内容不一定有效,具体取决于 Ptr 的定义方式:

cube_normals = new PointCloud<A>;  // but what do you do with the old pointer ?? 

假设您的智能指针 class 类似于:

template <class T>
class PointCloud {
public: 
    using Ptr = shared_ptr<T>;
}; 

然后您可以选择一个简单的:

cube_normals = PointCloud<A>::Ptr(new A); 

这个 compiles nicely,尽管根据您使用的智能指针的种类,使用 make_shared 或 make_unique 会更好。

我的建议是在 PointCloud 上工作,以确保正确的智能指针接口,包括保留指向空的指针,或者创建指向新对象的指针。