Hacker News new | past | comments | ask | show | jobs | submit login

> C++ constness is significantly more far-reaching and therefore more work to get right.

I'm not familiar with C++, can you explain more?




A const variable means that variable won't change. So `const int i = 6` means i will never change. But often you'll use pointers or references, these are C++'s way for a variable to point to data elsewhere. You can also make the pointers or references themselves const. Finally, you can make functions const too, which lets you turn C++ into half a haskell.

First pointers and references. For simplicitly I'm going to ignore references and focus on pointers - the difference is not very interesting in this context. In most languages you probably know, referring to objects is done implicitly: variables that "are" objects are actually references to objects located elsewhere, and variables that are primitive types (numbers, booleans, strings) are just right there. Because of this, in JavaScript you can do this:

    var a = {};
    var b = a;
    b.moo = 6;
    a.moo === 6; // true
In here, a and b point to some object that "is" neither a or b - the object itself just floats around in memory and it'll exist until neither a, b, nor anyone else points to it anymore and the GC decides it has to go.

In C++, you'll need pointers or references for this, eg.

    somestruct a;
    somestruct* b = &a; //b now points to a
    a.moo = 6;
    b->moo == 6; // true
(-> is just C++ shorthand for "follow the pointer and then do a property lookup).

Ok now const.

    somestruct const a;
    a.moo = 6; // error! can't modify a const.
Ok well how about

    somestruct a;
    somestruct* const b = &a;
    b->moo = 6;
    a.moo === 6; // true
This means the pointer is const. That works because we never change where b is pointing to. So how about:

    somestruct a;
    somestruct const* const b = &a;
    b->moo = 6;
    a.moo === 6; // true

Oh damn. Crying baby. Const functions will have to wait for some other day.


If you didn't want a to be mutated, you'd make it const in the beginning :)

Rust makes it much harder to make these kinds of erros by making variable ownership, reference lifetime, and const-by-default core to the language design. https://doc.rust-lang.org/book/ownership.html ... You do end up spending a lot of time "fighting the compiler," even compared to template-heavy C++ codebases, but the systems you create are free from an entire class of errors.


I'm not sure if you meant to imply otherwise, but your last example won't (and shouldn't) compile with clang/gcc.

clang++: error: cannot assign to variable 'b' with const-qualified type 'const somestruct *const'

g++: error: assignment of member ‘somestruct::moo’ in read-only object




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: