为什么智能指针类型的成员变量不能在类的声明处初始化?

发布于 2025-01-18 07:22:35 字数 398 浏览 2 评论 0原文

当我想向类中添加一个智能指针类型的成员变量时,我发现它无法在声明处初始化:

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

但我可以这样做:

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

看来智能指针与普通指针有很大不同,为什么会发生这种情况吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2025-01-25 07:22:35

std :: shared_ptr不能 copy-initialized 来自RAW指针,转换构造函数被标记为explicit

您可以使用 direct-initialization

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

或从std :::::::::: sharon_ptr

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

最好使用 std :: make_shared

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

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() {}
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文