Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a vectors unmodifiable when passing?

My wording might not be correct, but I hope you’ll understand what I mean.

Basically I have a map<enum class, vector<struct*>>. I want to pass the whole map without the vectors’ contents being modifiable.
I need the structs as pointers, because I save references to some of them e.g. to the player instance and they’ll get invalidated otherwhise.

It seems I can neither pass the map nor the vectors by reference. So this..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    std::map<myEnum, std::vector<const myStruct&>> getMap() {
        return myMap;
    }

..aswell as..

    const std::map<myEnum, std::vector<myStruct*>>& getMap() {
        return myMap;
    }

doesnt work.

Is there any way to solve this?

Sorry if the question is dumb, I’m kinda new to C++ and often don’t know what to search for.
Thanks for you help!

>Solution :

First of all, you should declare the member function itself const, otherwise it can’t pick the member function for the const circumstance when the object itself is const.

Second, you don’t have to think about the exact typing, you can let the compiler figure it out by saying const auto&. then it will return a constant reference, so it won’t be modifiable:

const auto& GameLogic::getMap() const {
    return myMap;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading