c++immutabilityimmutablelist

Immutable list in C++


How to make an immutable list in cpp? The list's reference should be constant as well as it's data.

I don't to make a wrapper class over vector or any other container (I know that method similar to this article).

What is the best way to do this using constexpr or const pointers.


Solution

  • Just declare it as const, like this:

    const std::list<int> constList = { 1, 2, 3 };
    

    Methods like constList.begin(); will return a const_iterator and calls like constList.push_back(3); will not compile.

    Assigning its address to a non-const pointer won't work:

    std::list<int> *l = &constList; // does not compile
    

    Passing a reference to a function that takes a non-const reference doesn't work:

    void a(std::list<int> &list) {}
    int main()
    {
        const std::list<int> mylist = { 1, 2, 3 };
        a(mylist); // does not compile
    }
    

    Not modifying the list is not a solution.

    Make a non-const list, and once you're done building it, move it to a const list:

    std::list<int> mylist = { 1, 2, 3 };
    mylist.push_back(4);
    const std::list<int> constList = std::move(mylist);