Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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() {}
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading