0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

c++でshared_ptrのクラス内宣言時初期化にはmake_sharedを使おう

Posted at

c++のshared_ptrはコンストラクタでポインタを受け取って初期化できます。
(ref: https://cpprefjp.github.io/reference/memory/shared_ptr/op_constructor.html)
なので、例えばnew int(3)を渡すことで、値が3で初期化されたintのshared_ptrを生成できます。

#include<iostream>
#include<memory>

int main(void){
  std::shared_ptr<int> hoge(new int(3));

  std::cout << *hoge << std::endl;
  return 0;
}
3

しかし、クラス内変数をこの方法で初期化しようとするとエラーが起きます。
(以下はg++の場合)

#include<iostream>
#include<memory>

class H{
  private:
    std::shared_ptr<int> hoge(new int(3));
  public:
    H(void){
      std::cout << *hoge << std::endl;
      return;
    };
};

int main(void){
  H h;

  return 0;
}
test11.cpp:6:31: error: expected identifier before ‘new’
     std::shared_ptr<int> hoge(new int(3));
                               ^~~
test11.cpp:6:31: error: expected ‘,’ or ‘...’ before ‘new’
test11.cpp: In constructor ‘H::H()’:
test11.cpp:9:21: error: invalid use of member function ‘std::shared_ptr<int> H::hoge(int)(did you forget the ‘()’ ?)
       std::cout << *hoge << std::endl;
                     ^~~~

どうやらshared_ptrを返す関数の宣言とみなされてるようです。
なので、make_sharedを使って初期化しましょう。

#include<iostream>
#include<memory>

class H{
  private:
    std::shared_ptr<int> hoge = std::make_shared<int>(3);
  public:
    H(void){
      std::cout << *hoge << std::endl;
      return;
    };
};

int main(void){
  H h;

  return 0;
}
3
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?