简体   繁体   English

与 const_cast 相反

[英]Opposite of const_cast

I have an std::vector<int*> v and I'd like to prevent further writes to it.我有一个std::vector<int*> v并且我想防止进一步写入它。 The C++ compiler does not accept this C++ 编译器不接受这个

const std::vector<const int*>& w = v;

but it accepts this但它接受这个

const std::vector<const int*>& w = reinterpret_cast<const std::vector<const int*>&>(v);

The latter does work with Microsoft's compiler, meaning that the int* inside v and const int* inside w have the same addresses in memory.后者确实适用于微软的编译器,这意味着v中的int*w中的const int*在 memory 中具有相同的地址。

Does this work by chance, as an unspecified behavior, or is it valid C++?这是偶然的,作为一种未指定的行为,还是有效的 C++? Does it work with all types inside the vector, like std::vector<std::shared_ptr<int>> ?它是否适用于向量内的所有类型,例如std::vector<std::shared_ptr<int>> If invalid, is there another way to do this cast?如果无效,还有其他方法可以进行此转换吗?

I know I could also copy the vector, but I'd like to avoid that, since my vectors are pretty big.我知道我也可以复制向量,但我想避免这种情况,因为我的向量很大。

This is Undefined Behavior.这是未定义的行为。

std::vector<const int*> and std::vector<int*> are two different classes (generated by the same template, but that is irrelevant). std::vector<const int*>std::vector<int*>是两个不同的类(由同一个模板生成,但这无关紧要)。 They cannot alias each other and you cannot reinterpret_cast between them.它们不能相互别名,并且您不能在它们之间reinterpret_cast

My solution is to use std::span :我的解决方案是使用std::span

const std::span s{const_cast<const int* const*>(v.data()), v.size()};

This will create a const std::span<const int* const> .这将创建一个const std::span<const int* const>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM