Immutable list in C++

1.7k Views Asked by At

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.

3

There are 3 best solutions below

4
On BEST ANSWER

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);
0
On

You can simply use it as a const std::list<T>. Both pointers in the following code will print out the same value.

#include <iostream>
#include <list>

using T = double;

void some_function(const std::list<T>& list) {
    const double * ptr = &(*list.begin());
    std::cout << ptr << "\n";
    //list.push_back(3.0);//error list is const
}

int main() {
    std::list<T> list{3.4,-42};
    const std::list<T>& const_list = list;
    const double * ptr = &(*const_list.begin());
    std::cout << ptr << "\n";
    //const_list.push_back(3.0);//error list is const
    some_function(list);
}
0
On

There is no exist immutable list ..if you want to make any list immutable then go for it -> "Create a wrapper named class whatever and create object of stl list inside wrapper class and dont provide any function inside the whatever class and play game with whatever's object..." now your list is immutable.