r/cpp • • Jul 29 '26

const_cast: A Necessary Evil

https://www.elbeno.com/blog/?p=1858
70 Upvotes

106 comments sorted by

View all comments

62

u/jwezorek Jul 29 '26

The only place I ever use const_cast is that idiom where you implement the non const version of a member function in terms of the const version.

37

u/MysticTheMeeM Jul 29 '26

If your language version allows, you can typically replace those with a single function that deduces this.

7

u/LeeHide just write it from scratch Jul 29 '26

Interesting, do you have an example?

8

u/Olipro Jul 29 '26

11

u/TheChief275 Jul 30 '26

why wasn't this added earlier? in fact, if this were to have been in C++ from the get-go, we never would have needed the postfix const syntax. so now we just have yet another language feature that virtually does the exact same thing. sigh

7

u/Expert-Map-1126 vcpkg maintainer BillyONeal Jul 30 '26

It was added mostly due to implementation experience after ref qualifiers were added trying to implement all the "transparent-ish" operations on optional et al.

I don't think it would completely replace the postfix syntax given that people expect names in members to refer to other members.

→ More replies (6)

2

u/serviscope_minor Jul 30 '26

> in fact, if this were to have been in C++ from the get-go, we never would have needed the postfix const syntax.

I don't get it? This really helps when you need a const and non const version of the same member function. If you don't (it's common that you have different mutating and const member functions) then const (or not) is better than deducing this.

→ More replies (3)
→ More replies (9)

3

u/_Noreturn Jul 30 '26

deducing this has issues with access soecifiers in inherited classes.

class C {
     public:
    void f(this auto && self) { self.dothing(); }
    void dothing();
    void dothing() const;
};

class P : private C {
    void g()
{
    f(); // error cannot access "dothing" from inside C::f;
}
}

3

u/XeroKimo Exception Enthusiast Jul 30 '26

Hmm, pretty interesting since only P should have access to members of C so even if this auto&& deduced a P, I would expect that to work, and if it instead deduces a C, I thought members of P should know that it can decay into a C

3

u/_Noreturn Jul 30 '26

It deduces to P& in the "f" call and thinks C is inaccessible this wouldn't happen if you manually typed the overloads. it is a sad known issue and it is why the C++ STL don't use deducing this (even though it was made to replace the absurd amount of boilerplate inside it)

you could friend the class C to get it to work iirc

class P : private C {
    friend class C;
// continue...

but it feels pretty wonky and then you have the issue of friendinf nit beinf transistive so if yiu inherit from P you will face the same issue

2

u/XeroKimo Exception Enthusiast Jul 30 '26 edited Jul 30 '26

Ah I guess that makes sense... You run into a similar problem if you tried to privately inherit a CRTP class and if any of the CRTP's member functions tries to cast to the derived class... So in deducing this' case, f() is a member function of C and if the this auto&& resolves to P, C doesn't have permission to access the C subobject in P...

If there was a way to constrain it so that the deduced type is always going to be C or any of the ref / const combinations this technique was intended to replace then I guess it'd be better.

→ More replies (1)

3

u/retro_and_chill Jul 30 '26

I learned the hard way that deducing this and protected member functions don’t mix

3

u/_Noreturn Jul 30 '26

Yes which is a shame :/

→ More replies (6)
→ More replies (3)

12

u/PolyglotTV Jul 29 '26

That and dealing with third party C libraries which like to just use void* or char* for everything even if it is a const operation in practice (looking at you Cuda...).

6

u/HildartheDorf Jul 29 '26

I've other time I've used it is with Vulkan where the query functions and creation functions use the same structure chains, so the structure chain types are defined with void *pNext not const void *pNext.

Creation functions do not modify the structure chain, so it's safe.

5

u/Tringi github.com/tringi Jul 29 '26

Quite a few Windows API functions are like that. Or they can do both setting and getting. If you implement only setting from a const buffer, then const_cast is appropriate.

3

u/HildartheDorf Jul 29 '26

In Vulkan's case the structure passed directly to the function is const-correct.
But the extensible structure chain can have dual-purpose types in it, and adding another item to the chain requires the const-cast. It's a mess however you solve it, the 'solution' would be a bunch of duplicate types that differ only in the constness of the pNext pointer.

6

u/usefulcat Jul 29 '26

There is at least one alternative that doesn't require const_cast:

struct S {
    std::vector<int> data;

    template<class Self>
    static decltype(auto) accessor_impl(Self& self, int i) {
        return std::find(self.data.begin(), self.data.end(), i);
    }

    // returns std::vector<int>::iterator
    auto find(int i) { return accessor_impl(*this, i); }
    // returns std::vector<int>::const_iterator
    auto find(int i) const { return accessor_impl(*this, i); }
};

Obviously this is a trivial and contrived example, but hopefully you can imagine more complex examples.

Personally I'd prefer to just use const_cast, as it's much simpler, but I'm concerned about the resulting UB.

8

u/Wacov Jul 29 '26

I don't think it's UB unless the thing you're accessing is actually const?

2

u/kisielk Jul 29 '26

It's fine if the thing is actually const, it's not fine if you then modify that that thing through the resulting non-const pointer.

3

u/bwmat Jul 30 '26

Isn't it fine because that can only happen if the caller had a mutable reference to the object in the first place?

If the object was originally const, the UB had already occurred? 

3

u/ts826848 Jul 30 '26

If the object was originally const, the UB had already occurred?

From what I understand forming a non-const pointer/reference to an actually-const object is fine. Its only the actual modification of said actually-const object that is UB.

→ More replies (3)

5

u/mort96 Jul 29 '26

What case is that? If you have a non-const this, you can call const member functions no problem since non-const pointers implicitly cast to const pointers, no?

4

u/sporule Jul 30 '26

Consider std::vector::at:

      T& at(size_t pos);
const T& at(size_t pos) const;

You can call the latter method on a non-const vector, but the return type would be wrong, and vec.at(0) = 1 would fail to compile.

So the way is to call the const version first and then cast constness away:

T& at(size_t pos) {
    return const_cast<T&>(std::as_const(*this).at(pos));
}

3

u/Raknarg Jul 29 '26

I use const_cast to interact with C APIs where context tells you if some operation will be const or not.

→ More replies (1)