c++ - 如何初始化作为类成员的智能指针?

标签 c++ smart-pointers

对 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,它将隐藏具有相同名称的类成员。

解决方案

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

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

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

假设你的智能指针类是这样的:

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 上工作,以确保正确的智能指针接口(interface),包括将指针保留为 null,或者创建指向新对象的指针。

关于c++ - 如何初始化作为类成员的智能指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40563901/

相关文章:

c++ - 最低 DirectX 9.0c 版本以及如何检查它

c++ - 我是否将 (int, double...) 视为类

c++ - C++ 中指向指针的替代方法?

c++ - 将 shared_ptr(this) 插入 vector 会导致 "free(): invalid pointer"错误

C++ 为什么它不是同一个地址(指针)

c++ - 我的 QThread 已完成,但我无法收到信号

c++ - 如何创建一个函数,它以任意函数指针作为参数?

c++ - std::sort 是否检查 vector 是否已经排序?

c++ - 创建 shared_ptr 到堆栈对象

c++ - Const 正确性、std 移动和智能指针