clicky
clicky

Reputation: 865

Shared pointer dereferencing error

Java guy here trying to get my head around C++, specifically shared pointers. I'm using the Point Cloud Library to do some surface work. The PCL library contains IndicesPtr which according to the documentation is a shared pointer on a std::vector.

How do I access the vector from the pointer? I have tried dereferencing with

pcl::IndicesPtr sample(new std::vector<int>());
...
for (int i = 0; i < *sample.size(); i++) { ... }

as per the documentation here https://theboostcpplibraries.com/boost.smartpointers-shared-ownership. Compiling then gives me the error

error: no member named 'size' in 'boost::shared_ptr<std::__1::vector<int, std::__1::allocator<int> > >'; did you mean to use '->' instead of '.'?
    for (int i = 0; i < *sample.size(); i++) {

What am I doing wrong here?

Upvotes: 0

Views: 905

Answers (2)

songyuanyao
songyuanyao

Reputation: 172864

According to operator precedence, operator. has higher precedence than operator*. So *sample.size() is same as *(sample.size()). That's why the compiler tried to tell you that you can't invoke size() on a boost::shared_ptr directly.

You can add parentheses to specify precedence explicitly, e.g. (*sample).size(); or as the compiler suggested, change it to sample->size().

Upvotes: 3

user7860670
user7860670

Reputation: 37468

It should either be (*sample).size() because operator . has higher precedence over dereference operator * or just sample->size().

Upvotes: 3

Related Questions