简体   繁体   中英

Opposite of const_cast

I have an std::vector<int*> v and I'd like to prevent further writes to it. The C++ compiler does not accept this

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.

Does this work by chance, as an unspecified behavior, or is it valid C++? Does it work with all types inside the vector, like 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). They cannot alias each other and you cannot reinterpret_cast between them.

My solution is to use 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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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