Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why smart pointer type member variable can't be initialized at the declaring place in a class?

When I want to add a member variable with smart pointer type to a class, I found that it can't be initialized at the declaring place:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = new int;  // not ok
  Foo() {}
};

But I can do this:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr;  // ok
  int* intPtr = new int; // ok
  Foo() {
    intSharedPtr.reset(new int);
  }
};

It seems that smart pointer is quite different form the normal pointer, Why this happens?

like image 513
Zhang Zheng Avatar asked Oct 18 '25 13:10

Zhang Zheng


1 Answers

std::shared_ptr can't be copy-initialized from raw pointer, the conversion constructor is marked as explicit.

You can use direct-initialization:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr {new int};
  Foo() {}
};

Or initialize from an std::shared_ptr:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = std::shared_ptr<int>(new int);
  Foo() {}
};

And better to use std::make_shared:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = std::make_shared<int>();
  Foo() {}
};
like image 178
songyuanyao Avatar answered Oct 20 '25 05:10

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!