chou chou - 28 days ago 10
C++ Question

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

Fairly new to C++ and so this is probably a really silly question. I need the

cube_normals
pointer to be accessed by both member functions
read_models()
and
proc_models()
, and the pointer must be initialized each time I call
read_models()
.

Inside the member function I could do :

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


I could pass the pointers to the other function but there are 12 such pointers I am using and its probably not the cleanest way to solve this problem.

This is the code snippet. Thanks in advance!

class preproc
{

public:

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

void read_models();
void proc_models();

private:

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

Answer

The problem

If inside the member function you have this statement:

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

you'll create a local variable cube_normals, which will hide the class member with the same name.

The solution

If the goal is to create a new empty object every time you call read_models() you could opt for an assignment.

The problem is that the following does not necessarily work, depending how Ptr is defined:

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

Assuming that your smartpointer class is something like:

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

You could then opt for a simple:

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

This compiles nicely, although it would be better to use make_shared or make_unique depending on the kind of smart pointer you're using.

My advice would be to work on PointCloud, to ensure a proper smartpointer interface, including resting a pointer to null, and ore create a pointer to new object.