4
4

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.

constメンバ関数から、同じクラスのメンバであるポインタの指す先は変更できる

Posted at

今まで知らずにC++書いてた
ヒィー(((゚Д゚)))ガタガタ

constメンバ関数から、同じクラスのメンバであるポインタの指す先は変更できる。(英訳したくない)
つまり、

class A{
    double* a;
public:
    void func() const{
        a[0] = 1.0;
    }
};

これはエラーにならない。

class A{
    double* a;
public:
    void func(double* b) const{
        a = b;
    }
};

これはエラー。つまりdouble * const a扱い。
std::vectorなら期待通りconst

class A{
    std::vector<double> a;
public:
    void func() const{
        a[0] = 1.0;
    }
};

はエラー。ちなみに

class A{
    std::unique_ptr<double[]> a;
public:
    void func() const{
        a[0] = 1.0;
    }
};

はエラーにならない。
つまりコンテナ使えってことですね、わかります。

4
4
0

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?