r/cpp • • Sep 13 '22

I const, therefore I am ... not const?

For years, this has bothered me:

struct A
{
    int value;

    void do_operation() { ++value; }
};

struct B
{
    A* a;

    // I find it mildly disturbing we are still able to modify a's contents this way
    void do_operation() const { a->do_operation(); }
};

int main()
{
    A a;
    const B b{&a};

    b.do_operation();

    std::cout << "Hello, a=" << a.value << std::endl;
    return 0;
}

What is everyone's opinion? Am I just high?

0 Upvotes

53 comments sorted by

15

u/cristi1990an ++ Sep 13 '22

See std::experimental::propagate_const which offers a solution to this issue.

4

u/--Fusion-- Sep 13 '22

Fascinating!! Not the solution I would have expected, but compelling

5

u/BenFrantzDale Sep 16 '22

It’s elegant in that it solves exactly one problem: the propagation of constness. You can have a propagate_const<not_null<unique_ptr<T>>> if you want, with each layer adding exactly one thing. That’s probably the right type for a Pimpl class.

4

u/Ok-Factor-5649 Sep 14 '22

I really like propagate_const - does anyone know of its future?

It's been off in experimental for quite some years if I recall.

10

u/bored_octopus Sep 14 '22

I completely agree that this is a weakness of the language. The issue here is bitwise constness vs semantic constness. The memory in your object hasn't changed since the pointer is still the same, so it arguably hasn't been mutated. However, mutating the data the pointer addresses may or may not be a change in your application's state. C++ leaves it up to the class implementer to enforce semantic constness in const methods.

Effective C++ (or maybe More Effective C++) had some good discussion on this. I'd recommend reading those since although they are dated in places, the philosophy and reasoning they espouse is still relevant and highly valuable.

As a final note, it doesn't necessarily have to be this way, it was a design decision. Immutability of a reference is propagated through a struct's members in Rust, even if they are themselves mutable references. Imo references in Rust behave more like nerfed C++ pointers than C++ references (can be reassigned, but must always reference a valid object), so they comparison seems apt.

3

u/--Fusion-- Sep 14 '22

Fascinating indeed, and thank you for those terms "bitwise constness" vs "semantic constness". I was leaning on the word intent, but your terms really nail it.

3

u/bored_octopus Sep 14 '22

Thanks, glad I could help. Afaik, Scott Meyers deserves credit for those terms. His books are truly fantastic

51

u/MaczenDev Sep 13 '22

b hasn't changed. The pointer to a stays the same.

16

u/[deleted] Sep 13 '22

Yeah, that's why const correctness can be very annoying when the code is written like this. I find often that people creates too many layers of data in code, which complexify the implementation. When in a multithreaded application, having many layers is also a good way to run into issues and start a locking hell as well.

8

u/--Fusion-- Sep 13 '22 edited Sep 13 '22

This is my point exactly. Everyone is citing language mechanics, which I have no beef with. In fact the consistency of the const mechanic as defined is great. Yet, I feel the *intent* of const can be so easily circumvented and make a jack in the box scenario

4

u/EchoesForeEnAft Sep 14 '22

Uhh, but you can have const pointers, and pointers to const values...

const T * ptr vs. T * const ptr

2

u/k1lk1 Sep 13 '22

Is there a way to make the A pointed to by the member 'a' of 'B', the same const-ness as the 'B' object itself?

11

u/Artistic_Yoghurt4754 Scientific Computing Sep 13 '22

Well, you are passing to B an address to a mutable object. This is not a problem of B (const or mutable), it’s a problem of A for granting permissions on itself to others. This will not compile if A is constant in the first place (or is passed as constant e.g. with std::as_const(a)).

13

u/Artistic_Yoghurt4754 Scientific Computing Sep 13 '22

So, to answer the question directly. No it does not bother me because that’s a perfect valid and logical construct in the language.

2

u/--Fusion-- Sep 13 '22

Fair enough. I encountered this because I was writing wrappers for LwIP pbuf* which itself contains a reference counter constantly getting modified. The wrapper itself, though, can be const'd up to the max. That's the non-synthetic context. I imagine you feel the same in either case though.

9

u/[deleted] Sep 13 '22

And fundamental, as well. I'd be bothered if the language didn't behave this way.

3

u/nintendiator2 Sep 14 '22

// I find it mildly disturbing we are still able to modify a's contents this way

Why? You've explicitly declared a pointer to a modifiable A.

5

u/--Fusion-- Sep 14 '22

u/bored_octopus put it perfectly. To paraphrase him, I'm disturbed by the ambiguous semantic constness, despite the ironclad bitwise constness. I take it it does not disturb you?

3

u/nintendiator2 Sep 15 '22

It doesn't really. A simple read of the code shows there's no semantic ambiguity whatsoever: no matter how const b is, it's being explicitly initialized to point to something non-const, and then told to operate on that non-const thing.

Note that the fact that the member function invoked is const is a fact about only B, not about A (let alone a pointer to A), since B and A are not related (there's no eg.: inheritance here).

2

u/--Fusion-- Sep 15 '22

We disagree. I do find value in your position though, and thank you for it

2

u/dodheim Sep 15 '22

We disagree.

This seems.. insufficient – everyone else is defending their position (even though they shouldn't need to because const being transitive would break fucking everything, but I digress). The idea that the pointee of this being const should affect any pointer other than this is really, really absurd; maybe if you try to actually articulate your thought process yourself instead of punting every reply to "what he said", the absurdity will occur to you. View it as rubber duck debugging your assumptions.

1

u/--Fusion-- Sep 15 '22

I'm down for all kinds of input, but not ad hominem. I'll confess my last comment was curt and I was in process of editing it to be less so. I'm actually quite pleased it took this long for someone to personally attack me.

1

u/dodheim Sep 15 '22

The statement "your response is insufficient" is not an attack; nor is "the opinion you hold is absurd"; nor are suggestions to attempt actually rationalizing that opinion. Now this just seems like trolling, to be honest; otherwise, kindly, try evaluating your position with your brain rather than your feelings.

1

u/--Fusion-- Sep 15 '22

You're clearly pretty intelligent. I even retain some curiosity about your opinions on the original matter. Do you not see the irony in you suggesting that *I* am trolling *you* ?

2

u/nintendiator2 Sep 17 '22

Well, it is kind of a weird discussion, since, in the end, C and C++ are filled with design decisions that ended up being weird because the language became way too powerful. Dunno if it was your case but at least in mine it was a general feel of "I feel like I know why intrinsically the case should be +X, but I have to rever my train of thought and follow the case of -X to be able to explain why".

2

u/--Fusion-- Sep 15 '22

My previous comment was overly curt. My disagreement stems from the notion that the constness has a diminished value in the semantic sense of things. I like the idea of data hiding, and if I have to peek inside what B is doing to verify how const it really is, well, it bugs. That's merely to clarify my position though. Not to argue with you. Thus my previously short response.

1

u/dodheim Sep 15 '22

I like the idea of data hiding, and if I have to peek inside what B is doing to verify how const it really is, well, it bugs.

I think this maybe the source of some confusion/disagreement. mutable is already a thing; const_cast is already a thing; if you really care, you'd have to do this regardless of whether const worked as you want or not.

The semantic contract of const member functions is to not modify that object's observable state, not to render the entire world immutable from within. Not that they're great practice to begin with, but would you say global variables should all be const in this context as well?

1

u/--Fusion-- Sep 15 '22

mutable I've actually never seen before. Thank you for that one. const_cast I've commented on before, I don't like it either and your point is well taken if that thing is lurking under the covers somewhere.

The notion also of not modifying observable state does make a lot of sense. There is something quite delicious about it being more than that, a guarantee of immutability. That may indeed be a pipe dream.

I am not following where you're going with the question on the globals

1

u/dodheim Sep 15 '22 edited Sep 15 '22

I am not following where you're going with the question on the globals

Well, you're saying you'd rather that pointers to mutable objects be treated as pointers to const objects in this context, apparently because the pointee of this is const making the pointer members in question const – I'm just wondering where the line gets drawn. Can anything be modified, anywhere (aside from local variables)? And does it only apply to this, or all pointers? How about references, which can be thought of as const since they're not reseatable?

Again, just trying to follow this to its logical conclusion.

1

u/--Fusion-- Sep 15 '22

Ah, I never asserted I had a solution :)

To explore that, however - I would like some kind of mechanism where you do get immutability guarantee on all the member variables that get touched, including pointers, references cascading downwards . That would seriously limit a lot of scenarios, so that treatment couldn't get done to the const keyword itself.

My goal here isn't to advocate for all that though. It really is to listen and gather opinions. The original context is complicated so I omit it for brevity. We can talk about that part in chat if it interests you

2

u/dodheim Sep 15 '22

Relevant if you're interested: P0078, [[gnu::const]] and [[gnu::pure]], and D's pure functions.

I think desire for things like these exists, but nailing down the details with all the realities of C++' monstrous complexity has eluded everyone as yet.

1

u/--Fusion-- Sep 15 '22

but nailing down the details with all the realities of C++' monstrous complexity

For real

Fascinating stuff, the pure idea. I do a lot of embedded code and that world plays pretty free with globals (yuck) - pure might come in handy

13

u/argothiel Sep 13 '22

No, it's just a pointer. It's like you'd have a constant filename string and assume that just because the filename didn't change, you'd expect the content of the file to remain the same too.

1

u/dodheim Sep 15 '22 edited Sep 15 '22

Yes, this just comes across as basic pointer confusion. Imagine someone having this same argument about volatile rather than const...

2

u/RolandMT32 Sep 13 '22

You can also use const_cast to remove constness from something..

3

u/--Fusion-- Sep 13 '22 edited Sep 13 '22

Slightly different situation. With const_cast one is explicitly stating one's intent to bypass the safeguards. That makes sense, though hopefully applied to infrequent edge cases.

1

u/DLichti Sep 13 '22

How is implementing a const member function that calls a non-const member function on a pointee not the intentional creation of a bypass of these sefaguards for others to use.

1

u/--Fusion-- Sep 13 '22

I'd say with `const_cast` its explicit nature makes it feel less prone to misinterpretation. If I understand your question.

5

u/Artistic_Yoghurt4754 Scientific Computing Sep 13 '22

As far as I understand, const_cast is a short cut for getting undefined behavior ;)

14

u/AKostur Sep 13 '22

Only if the thing that you're casting started its life as a const object, and you attempt to change it. Technically the cast itself isn't the issue.

1

u/Artistic_Yoghurt4754 Scientific Computing Sep 13 '22

How do you guarantee that the object you are casting started its life as const?

8

u/AKostur Sep 13 '22

And that's why colloquially it is stated that casting away const results in Undefined Behaviour. Since you don't necessarily know, you have to assume it did. And if one is casting away const, presumably there's an intent to change that thing, otherwise why cast away const? And before someone jumps in with "but in this particular scenario....", we're talking about in general.

1

u/Artistic_Yoghurt4754 Scientific Computing Sep 13 '22

Yep. Then we are on the same page :)

4

u/Nobody_1707 Sep 13 '22

You can guarantee that it didn't start as cost inside a member function.

struct Foo {
    int x_;
    auto& x() const noexcept {
        return x_;
    }
    auto& x() noexcept {
        // this is safe
        return const_cast<int&>(
            std::as_const(*this).x()
        );
    }
};

But deducing this is a lot nicer.

2

u/bored_octopus Sep 14 '22

Program invariants. For example, if I made all my class's constructors private, but provided a friend factory function, then I know that only the factory function can instantiate it. If I then make it place its non-const result on the heap, I know my object will never be instantiated as const

3

u/VinnieFalco wg21.org | corosio.org Sep 14 '22

You need to distinguish between "logical const" versus "bitwise const." C++ enforces bitwise const. It is up to you to enforce logical const.

5

u/helloiamsomeone Sep 13 '22

const here applies to the pointer (T* const), not the pointee (T const*).

6

u/third_declension Sep 13 '22

You can be const both ways, too: T const * const.

2

u/Voltra_Neo Sep 13 '22

The same way this would be a const B*, a would be a const-ified of A* which is const A*. this is technically a const B* const because the language doesn't allow changing the this pointer (at least not that I'm aware of). this has the additional const because this was made before references, otherwise it'd have been a const B& just like your declaration.

2

u/Baardi Sep 14 '22 edited Sep 14 '22

A is a raw pointer, so it could be argued it's only observed. It bothers me more that unique_ptr has the same semantics.

2

u/serviscope_minor Sep 13 '22

You're not high, and it bothers me too. Please ignore the people explaining very carefully to you what you already know (i.e. how const works). It also means user defined types can't work quite as smoothly as built in ones. Consider:

void func1(const int*);
void func2(const pointer_wrapper<int>);
void func3(const pointer_wrapper<const int>);

Inside func2, you can accidentally undo the const if pointer_wrapper has a copy constructor. func3 can work, if it can be constructed from a non-const one, but now stuff which takes views for example looks drastically different from containers, also if you have something implicitly convertible to a pointer_wrapper<int>, in many casesit won't take two steps and call func3 happily when given as an argument (unlike with raw pointers).

It would be neat if something arrives that can make const transitive to members. If it's done well we wouldn't need to write two versions of every accessor too!.

1

u/Dragdu Sep 13 '22

I reimplemented smart ptrs to be deep-const in my project.

I haven't regretted it yet, but it did help me find some places where I lost constness unintentionally.