const int *
とint *const
は非常に異なります。同様にconst std::auto_ptr<int>
対std::auto_ptr<const int>
と同様です。しかし、const std::vector<int>
とstd::vector<const int>
との区別はありません(実際には2番目が許可されているかどうかはわかりません)。どうしてこれなの?なぜstd :: vectorは含まれているオブジェクトにconstnessを渡しますか?
時々私はベクトルへの参照を渡したい機能を持っています。この関数はベクトル自体を変更すべきではありません(例えば、no push_back()
)が、含まれている値のそれぞれを変更したいとします。同様に、ベクトル構造を変更するだけで、既存のコンテンツを変更することはできません(これは奇妙ですが)。この種のものは、(例えば)std::auto_ptr
で可能ですが、std::vector::front()
(例えば)は
const T &front() const;
T &front();
だけではなく、
T &front() const;
これを表現する方法はありませんように定義されているため。私が何をしたいの
例:
//create a (non-modifiable) auto_ptr containing a (modifiable) int
const std::auto_ptr<int> a(new int(3));
//this works and makes sense - changing the value pointed to, not the pointer itself
*a = 4;
//this is an error, as it should be
a.reset();
//create a (non-modifiable) vector containing a (modifiable) int
const std::vector<int> v(1, 3);
//this makes sense to me but doesn't work - trying to change the value in the vector, not the vector itself
v.front() = 4;
//this is an error, as it should be
v.clear();
私は誰もこれについて言及していませんが、ポインターのconstベクトルはポインターが指すオブジェクトを変更することを可能にし、必要に応じて回避策として使用できます。 –