1

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.

  • My go to smart pointer is `std::unique_ptr`. The `std::shared_ptr` is the one I use a the pointer-of-last-resort, because a shared_ptr has federated ownership which (assuming it doesn't hold a `const` type) is tantamount to a **mutable global**. Which makes the code harder to reason about, and susceptible to spooky action at a distance bugs. – Eljay Sep 01 '22 at 11:22

2 Answers2

4

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
3

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) {}
fadedreamz
  • 1,156
  • 1
  • 10
  • 19