小编Zha*_*eng的帖子

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

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

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

但我可以这样做:

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

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

c++ initialization class smart-pointers copy-initialization

4
推荐指数
1
解决办法
218
查看次数