简体   繁体   中英

I want to put a pointer to an object that is const into a container that holds non-const pointers. What are my options?

I have some code that looks like this:

void addPtrs(vector<Thing*> & ThingPtrs, const vector<Thing> & actualThings) {
       for (const Thing & t : actualThings)
           if (/*some condition*/)
               ThingPtrs.push_back(&t);
}

Basically, I want to modify ThingPtrs by giving it pointers to Thing s that have some condition. However, because I do not want to modify the actual Thing , I labeled actualThings as const , and now I can't assign a const pointer to a non const pointer.

Obviously one solution is to simply not make actualThings const , but I don't actually intend to modify it. Another solution is using a const_cast , but I would like to avoid that if possible too.

What are my options in a situation like this?

By design, const std::vector will not allow you to modify it's elements directly. Since actualThings is const you cannot modify it's content. Any reference or pointer to it's elements will be const.

Any solution you find without changing the function's prototype will ultimately involve converting a const Thing & or const Thing * to it's non-const equivalent, regardless of how you dress it. Any pointer cast or reinterpretation would just be a round-about const_cast .

If you are concerned that addPtrs does not modify actualThings (in the sense of calling it's non-const member) you could change your interface to accept a begin/end pair of iterators. Other changes that will allow your function to compile include removing const from actualThings to get vector<Thing> & actualThings or adding const to the type of elements in ThingPtrs to get vector<const Thing*> & ThingPtrs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM