Search code examples
c++smart-pointers

no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argument


when operating smart pointers, something confused me.

Hers is the error message

no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argument

and here's the code I ran

#include <memory>
#include <vector>

class test {
public:
  int x_;
  test(int *x) {}
};

int main(int argc, char *argv[]) {

  auto x = std::make_shared<int>(5);
  std::shared_ptr<test> t = std::make_shared<test>(x);
}

I think this error came from the different types of pointers. And compilation can succeed when changing

std::shared_ptr<test> t = std::make_shared<test>(x);

into

std::shared_ptr<test> t = std::make_shared<test>(&(*x));

But this operation &(*), in my opinion, looks weird. I'm not sure that is a common usage when people program.

Is there any suggestion for this question? Thanks.


Solution

  • Use x.get().

    It's not implicitly convertible because that would make it too easy to make mistakes, like creating another shared_ptr from the same raw pointer without proper sharing.