8
12

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 5 years have passed since last update.

unique_ptrのメンバ変数のGetter/Setter

Last updated at Posted at 2017-02-27

C++11でunique_ptrなメンバ変数に対するGetter/Setterの書き方。

class B {
public:
    B() {}
    ~B() {}
};

class A {
public:
    const B& GetData() const {
        if (!m_data) {
            throw std::domain_error("null pointer");
        }
        return *m_data;
    }

    void SetData(std::unique_ptr<B>&& new_data) {
        m_data = std::move(new_data);
    }

private:
    std::unique_ptr<B> m_data;
};

int main(void) {
    A obj;

    std::unique_ptr<B> data1(new B());
    obj.SetData(std::move(data1));

    const B& b1 = obj.GetData();

    return 0;
}

Getterはconst参照で返す。理由は、

  • 所有権を渡すわけではない。

m_dataがnullptrの場合は例外投げておく。

Setterは右辺値参照を引数にとり、moveしてメンバ変数に設定する。理由は、

  • 引数の型をunique_ptr<B>の値渡しにすると、仮引数に渡すときにunique_ptrのムーブコンストラクタが呼ばれるので無駄。
8
12
8

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
8
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?