How to make a list and its const content in c ++?

advertisements

If I have a:

class myClass
{
...
list<myObject*> objectList;
};

How can I write a getObjectListPointer() function that return a pointer to this objectList in a way, that itself and its content cannot be modified?

Which means, if I have

list<myObject*>* pointer = getObjectListPointer();

then pointer itself and pointer->at(i) for any i cannot be modified? Like where should I put const?


Ok, my purpose is to able to modify objectList with in myClass but not other places, but I need to access the value of objectList and its content's value in other class, how should design the code?


With

struct myClass
{
    std::list<const myObject*> getObjectListPointer() const
    {
        // Create a copy with const pointers
        return {std::begin(objectList), std::end(objectList)};
    }

    std::list<myObject*> objectList;
};

You may then do

myClass instance;
const auto& pointer = instance.getObjectListPointer();
// cannot modify list `objectList`, and all `myObject` would be `const`