请参阅下面的代码 - 我试图将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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
EDIT2 :(删除了一堆不必工作的东西)C++ 11标准规定了insertfor vector和deque(以及push_back那个问题的默认实现)的方法需要值类型CopyAssignable,即值支持:
t= v;
Run Code Online (Sandbox Code Playgroud)
默认情况下,具有const成员的类和结构不是CopyAssignable,因此您要执行的操作将不起作用.
该doc (n3173)解释了各种容器要求.
| 归档时间: |
|
| 查看次数: |
4707 次 |
| 最近记录: |