Home > Software engineering >  no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argumen
no known conversion from 'std::shared_ptr<int>' to 'int *' for 1st argumen

Time:09-02

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.

CodePudding user response:

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.

CodePudding user response:

You are trying to pass std::shared_ptr<int> to a constructor accepting int *. There is no implicit conversion for it.

You have two choices -

  1. change to std::shared_ptr<test> t = std::make_shared<test>(x.get());
  2. or change the constructor to test(std::shared_ptr<int> x) {}
  • Related