C++ 如何将 std::vector<int> 转换为 const std::vector<const int>?

Ziq*_*Liu -4 c++

我想投一个std::vector<int>to const std::vector<const int>,好像不能自动投。所以我有一些问题:

  1. 我可以很容易地投射std::vector<int>const std::vector<int>,这是为什么呢?

  2. 如果我想投射到const std::vecor<cosnt int>,我该怎么做?我试过 const_cast 但没有用

Xir*_*ema 6

如果我想投射到const std::vecor<cosnt int>,我该怎么做?我试过了,const_cast但没有用

简短的回答:不要。

当你创建一个std::vector<int>const, as-in 时const std::vector<int>,内容本身也变得隐含const了。换句话说,如果你写这样的东西,你将无法修改元素:

const std::vector<int> values{1,2,3,4,5};

//Nope
//values.emplace_back(6);

//Also Nope
//values[3] = 5;

//Still nope
//values.erase(values.begin() + 1, values.begin() + 3);

//Nuh-uh
//std::vector<int> & mutable_values = values;

//This, however, is okay.
std::vector<int> const& immutable_values = values;

//Same restrictions though
//immutable_values[2] = 6;
//immutable_values.emplace_back(7);

//This is fine
std::vector<int> copy_of_values = values;

//But that's because you made a copy
copy_of_values.emplace_back(6);
assert(copy_of_values.size() != values.size());
assert(copy_of_values != values);
Run Code Online (Sandbox Code Playgroud)

这就是为什么像std::vectorstd::list、等 STL 容器std::map禁止const在其模板参数列表中使用成员的原因:因为制作容器本身const也会制作其内容const,这是这些容器设计的约定。一些“容器”没有这个属性,比如智能指针,这就是为什么你有时会看到这样的东西:

std::shared_ptr<int> ptr = std::make_shared<int>(42);
std::shared_ptr<const int> non_modifying_ptr = ptr;
Run Code Online (Sandbox Code Playgroud)

这是引用计数指针核心功能的一部分。

顺便说一句,这是确保您的代码“const-正确”的全部内容,我强烈建议您对该主题进行谷歌搜索并了解它是什么,以及如何在您的代码中正确应用它以您的代码更安全、更高效。

  • @AlbertoMiola 实际上,这将是未定义的行为。如果你***知道***对象最初没有声明为`const`,那么`const_cast`去掉对象的`const`是完全合法的,但是如果对象*被*声明为`const`,那么它是UB,并且不安全。 (2认同)