Why would const change the type? Wouldn't that make any const_cast UB?
-
-
Vastauksena käyttäjälle @Bobby_Anguelov
It seems to me that the two vector types are unrelated. So they may as well be struct A{}; and struct B{}; It seems that you may as well be doing: A a; B& b = (b&)a; which I believe is UB.
1 vastaus 0 uudelleentwiittausta 0 tykkäystä -
Vastauksena käyttäjälle @tloch14
Why do you think that? Nothing in the vector itself changes (ptr + size) and the type pointed to also doesn't change. Just the access semantics. Afaik. I can const_cast a const int and modify it without it being UB. Right?
2 vastausta 0 uudelleentwiittausta 0 tykkäystä -
Vastauksena käyttäjälle @Bobby_Anguelov
The compiler is free to reorder members within a class regardless of the order they were declared in. No implementations do (that I know of), but we aren't asking about implementations.
2 vastausta 0 uudelleentwiittausta 0 tykkäystä -
Vastauksena käyttäjille @tloch14 ja @Bobby_Anguelov
I guess, all that being said, I gave it a shot in godbolt with -fsanitize=undefined and it didn't return any errors. *shrug*. If it were me, I'd use a span<int const *>.
3 vastausta 0 uudelleentwiittausta 0 tykkäystä -
Vastauksena käyttäjille @tloch14 ja @Bobby_Anguelov
At risk of inciting a mob, those who follow
@lefticus may be best equipped to answer this.1 vastaus 0 uudelleentwiittausta 0 tykkäystä -
Vastauksena käyttäjille @tloch14 ja @Bobby_Anguelov
Yes, they are two completely unrelated types, and it is UB. Breaks strong aliasing rules. Most uses of const_cast enable UB and almost all uses of reinterpret_cast result in UB, and your c-style cast is a reinterpret_cast. I'll let
@shafikyaghmour link his articles3 vastausta 0 uudelleentwiittausta 4 tykkäystä -
So what's the most performant way to get a const version of those pointers in an array format? Std::span? And before c++20?
1 vastaus 0 uudelleentwiittausta 0 tykkäystä -
I'd need more context for what you intend to do with them, but span can be implemented pretty simply in even C++14, and should do what you want
1 vastaus 0 uudelleentwiittausta 0 tykkäystä -
I have a vector of ptrs that I need to return in a read only format (I.e.) users aren't allowed to modify any data pointed to. I am assuming the span is also doing a const cast internally to go from: Std::vector<foo*> to std::span<foo const*> Right?
2 vastausta 0 uudelleentwiittausta 0 tykkäystä
The difference is that casting from foo* to foo const * is not really a cast. The pointer is copied to a compatible type. Casting the vector<foo*> to a vector<foo const*>& is a reinterpret cast from one type to an unrelated type (despite them both being of the same template).
Lataaminen näyttää kestävän hetken.
Twitter saattaa olla ruuhkautunut tai ongelma on muuten hetkellinen. Yritä uudelleen tai käy Twitterin tilasivulla saadaksesi lisätietoja.