【发布时间】:2013-04-20 18:27:51
【问题描述】:
我喜欢将我的 C++ 成员变量设置为 const,如果它们在构造对象后不应更改,但是,有时它们需要由 STL 修改。例如,如果我有一个包含 const 成员的类的向量,并且我尝试交换向量中的两个元素,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.
【问题讨论】:
-
如何在保留
const的同时交换两个元素? -
IMO,尝试这样做会出现问题:一个 const 对象(顺便说一句,您可能会争辩说您不应该公开此数据成员)说“我不会改变我的可观察行为”。现在,如果有人拥有指向容器中某个元素的指针/引用或迭代器,而您替换了该元素,那么可观察到的行为就会发生变化。
-
@AlexChamberlain
swap(T& lhs, T& rhs) { T tmp_lhs(lhs); lhs.~T(); new(&lhs)(rhs); rhs.~T(); new(&rhs)(tmp_lhs); }在创建和销毁之间没有修改任何对象! ;) -
@yakk 现在,让它异常安全!
-
@didierc 我们有一个
T的容器。我们正在四处移动。切片不是问题。
标签: c++ c++11 constants assignment-operator c++03