掲示板システム
ホーム
アクセス解析
カテゴリ
ログアウト
privateメンバーの書き換えを防止するには? (ID:63367)
名前
ホームページ(ブログ、Twitterなど)のURL (省略可)
本文
privateなメンバー変数として文字列や別のオブジェクトを持っている場合に それへの参照を返すpublicなメンバー関数を作りたいのですが 使用時にconstを外されるとメンバー変数を書き換えられてしまいます。 これを防ぐ良い方法はないでしょうか? あきらめてコピーインスタンスを返すべきでしょうか? 環境:VC++ 2005 コード例: ------------------------------------------------- #include <iostream> #include <string> class hoge { public: hoge( const std::string& s ) : m_str( s ) {} const std::string& GetStr() const { std::cout << "m_str: " << m_str << std::endl; return m_str; } private: std::string m_str; }; int main( int argc, char* argv[] ) { hoge h( "aaa" ); const std::string& ss = h.GetStr(); std::cout << "ss: " << ss << std::endl; const_cast<std::string&>( ss ) = "bbb"; // 危険 std::cout << "GetStr: " << h.GetStr() << std::endl; } ------------------------------------------------- 結果: ------------------------------------------------- m_str: aaa ss: aaa m_str: bbb GetStr: bbb -------------------------------------------------
←解決時は質問者本人がここをチェックしてください。
更新する
戻る
掲示板システム
Copyright 2021 Takeshi Okamoto All Rights Reserved.