以下のコードを見てください。私はベクトルにconstオブジェクトを入れようとしています。私は答えが「STLコンテナは、オブジェクトを割り当て可能でコピー可能でなければなりません」ということを知っていますが、標準を引用することなく、誰でもこれを行う問題が何であるか説明できますか?私はなぜこのようなクラスをコピーできないのか理解できません。(それ以外にもC++は許可しません)。なぜSTLコンテナにconstオブジェクトを置くことができないのですか?
変更が許可されていない値が格納されています。なぜ、ベクターに入れることができないのですか?単にこれらのオブジェクトの別のものを作成するだけですか?
#include <vector>
// Attempt 1
// /home/doriad/Test/Test.cxx:3:8: error: non-static const member ‘const int MyClass::x’, can’t use default assignment operator
// struct MyClass
// {
// int const x;
// MyClass(int x): x(x) {}
// };
//
// int main()
// {
// std::vector<MyClass> vec;
// vec.push_back(MyClass(3));
// return 0;
// }
// Attempt 2
// /home/doriad/Test/Test.cxx:28:23: error: assignment of read-only member ‘MyClass::x’
struct MyClass
{
int const x;
MyClass(int x): x(x) {}
MyClass& operator= (const MyClass& other)
{
if (this != &other)
{
this->x = other.x;
}
return *this;
}
};
int main()
{
std::vector<MyClass> vec;
vec.push_back(MyClass(3));
return 0;
}
EDIT:
はstd ::設定とstd ::リストでこれを行うことが可能です。私はそれが割り当てを使用するstd :: vectorのsort()関数だと思います。これはUBの権利ではないのですか?
#include <set>
// Attempt 1
struct MyClass
{
int const x;
MyClass(int x): x(x) {}
bool operator< (const MyClass &other) const;
};
bool MyClass::operator<(const MyClass &other) const
{
if(this->x < other.x)
{
return true;
}
else if (other.x < this->x)
{
return false;
}
}
int main()
{
std::set<MyClass> container;
container.insert(MyClass(3));
return 0;
}
Semi-related:http://stackoverflow.com/questions/2759350/embarassing-c-question-regarding-const/2759426#2759426 – cHao
std :: vectorの代わりにstd :: setを使って私の編集を見てください。これでいい? –
@David:C++ 03では、 'std :: set <>'を使っているように、依然として不正です - §23.1/ 3では、要素型はコピーコンストラクタブルとアサイン可能でなければなりません。 C++ 11では、コードは整形式ですが、 'MyClass'が代入不可能なため、' std :: set <> 'インスタンスは代入されません。 (また、セミ関連: 'operator-'実装は壊れています、 'this-> x == other.x'なら値を返しません)。 – ildjarn