chou chou - 1 year ago 109
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

pointer to be accessed by both member functions
, and the pointer must be initialized each time I call

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


PointCloud<A>::Ptr cube_normals;

void read_models();
void proc_models();


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

Answer Source

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 {
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download