Search code examples
point-cloud-librarypoint-clouds

Could anyone tell something about using ::Ptr and new operator when using PCL


I tried to declare an object of a PCL class with

typedef pcl::PointCloud<PointNT> PointCloudT;   // in the .h file.

and

PointCloudT::Ptr object = new PointCloudT();   // in main func
PointCloudT::Ptr scene = new PointCloudT();    // and these two triggers the error of

1>f:\cpps\pclrclass\pclrclass\main_routine.cpp(10): error C2440: 'initializing' : cannot convert from 'PointCloudT *' to 'boost::shared_ptr>'

but it works if the declaration is given by

PointCloudT::Ptr object(new PointCloudT);   // in main func
PointCloudT::Ptr scene(new PointCloudT);    // works and correct

I am not good at C++ and don't know what the problem is of this error. Could anyone tell a little about it.


Solution

  • The new PointCloudT() expression yields a raw pointer to a point cloud, PointCloudT *.

    PointCloudT::Ptr is a synonym for boost::shared_ptr<PointCloudT>, a smart pointer to a point cloud. You can look up the synopsis of this template class here. As you can see, it has a constructor

      template<class Y> explicit shared_ptr(Y * p);
    

    which in our case becomes

      explicit shared_ptr(PointCloudT * p);
    

    This means that it can be constructed from a raw pointer to a point cloud. Note the explicit keyword, which forbids implicit construction and copy-initialization.

    This is why the first snippet gives error (you request implicit conversion between two different classes), and the second snippet works (you explicitly call the constructor of shared pointer).