我喜欢将我的 C++ 成员变量设置为 const,如果它们在构造对象后不应更改,但是,有时它们需要通过 STL 进行修改。例如,如果我有一个包含 const 成员的类的 vector ,并且我尝试交换 vector 中的两个元素,STL 会尝试使用默认生成的 operator=()
并且由于 const 成员而失败变量。
我觉得 operator=()
就像一个构造函数,它正在创建整个对象,因此希望有一些方法允许 operator=()
同时仍然有我的 const 成员变量。
在 C++03 中有没有办法做到这一点?如果不是,那么在 C++11 中,也许就地构造就是为此目的?
class Foo {
const int _id;
static int _generate_unique_id();
public:
Foo()
: _id(_generate_unique_id()) {
}
};
vector<Foo> foo_vector;
// Fill foo_vector with several entries:
// [...]
// Try to swap the first and second elements of the vector:
swap(*foo_vector.begin(), *(foo_vector.begin() + 1));
// The above fails to compile due to const member variable _id
// prohibits us from using the default assignment operator.
最佳答案
在标准库容器中存储不可分配对象的解决方案是存储指向对象的(智能)指针。并不总是理想的,但可行。
关于c++ - 如何在 C++ 的 STL 容器值中拥有 const 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238836/