c++ - 如何在 C++ 的 STL 容器值中拥有 const 成员?

标签 c++ c++11 constants assignment-operator c++03

我喜欢将我的 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/

相关文章:

c++ - 将传递的参数限制为字符串文字

C++ 使用 Const int 定义数组

javascript - 使用 const 创建动态变量

c++ - const成员函数如何改变对象的数据?

C++ boost::graph从有向图中获取父顶点

c++ - 区分 C++ 中基指针 vector 中的派生对象

c++ - 派生类型名

c++ - 为什么通过引用传递从 std::function 派生的对象会使程序崩溃?

c++ - 为什么显示 "Received a connection from 0.0.0.0, port 0"?

c++ - 是否应该评估或存储循环限制?