続 C++ の const の問題点
の続き.
const 記憶域に配置されたオブジェクトのコンストラクタ内から,非 const なポインタを取り出せそうにみえる.こんなのも合法なんだろうか.C++ むずい. (追記) Unspecified らしい.kinaba さんに教えてもらった.文末にも追記.
class X { public: X(X **ptr) { *ptr = this; } private: int dummy_; }; X* xptr = NULL; const X x(&xptr);
他の例.const メンバ関数の中で,メンバから読み出した値を使って環境を書き換えたら,その結果として自分自身が書き換わるようなケース.C++ むずい.
#include <iostream> class Hauhau { public: Hauhau() : age_(0), ageptr_(&age_) {} void ThisIsAConstMemberFunction() const { ++(*ageptr_); } int GetAge() const { return age_; } private: int age_; int *ageptr_; }; int main() { using namespace std; const Hauhau hauhau; cout << hauhau.GetAge() << endl; hauhau.ThisIsAConstMemberFunction(); cout << hauhau.GetAge() << endl; return 0; }
本当に書き換わって欲しくなければ,
class Hauhau { // (略) private: const int age_; };
とでもしておけということか.
追記
.@NyaRuRu 仕様としては、constとして配置した値のコンストラクタでのthisを外に渡すと、そのポインタを使って操作された値はunspecified (
12.1.512.1.15) になります。
@kinaba おおっ,ありがとうございます.ちなみにthisそのものを外に渡す以外に,&(this->foo) みたいなのを外に渡してもやっぱりunspecifiedなんでしょうか?
.@NyaRuRu はい、"if the value of the object or ~~any of its subobjects~~ is accessed through thisから作った以外の左辺値" が unspecified になる条件でした
後半も原文を引用すると "through an lvalue that is not obtained, directly or indirectly, from the constructor's this pointer"