【发布时间】:2011-12-31 00:04:13
【问题描述】:
请参阅下面的代码 - 我正在尝试将 const 对象放入向量中。我知道答案是“STL 容器要求对象是可分配的和可复制的”,但是,在没有引用标准的情况下,谁能解释这样做的问题是什么?我不明白为什么不能复制这样的类(除了 c++ 不允许这样做)。
它只是一个不允许更改的存储值 - 为什么不能将它放入向量中简单地创建另一个对象?
#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;
}
编辑:
使用 std::set 和 std::list 可以做到这一点。我猜是 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;
}
【问题讨论】:
-
请查看我使用 std::set 而不是 std::vector 的编辑。这样可以吗?
-
@David :在 C++03 中,像这样使用
std::set<>仍然是错误的——§23.1/3 规定元素类型必须是可复制构造的 和 i> 可分配的。在 C++11 中,您的代码格式正确,但您的std::set<>实例将不可分配,因为MyClass不可分配。 (另外,只是半相关的:你的operator<实现被破坏了,因为如果this->x == other.x它不会返回任何值)。 -
ildjarn - 你是对的操作员
标签: c++