对 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/