简体   繁体   中英

top-level const with pointers

Suppose that I have class which has std::vector<Object*>

Should method like:

const std::vector<Object*> getSth() const
{
    return class_member_vector;
}

be converted to:

std::vector<Object*> getSth() const
{
    return class_member_vector;
}

It is always safe and should be always corrected in that way?

Yes, you should use the second variant for clarity. And yes, this is always safe. In both variants you are returning the return value by value , so the class cannot be affected by modifying the returned vector. Also in both cases the callee can modify the objects pointed to by the vector elements, so the outer const does not make a difference there either.

The const in the first variant is misleading and should be removed.

But you may want to consider to return a const std::vector<Object*>& reference for performance reasons. It depends on your use model of the class (eg lifetime, scope) whether this is a good idea or not. Performance wise it is a good idea to return by const reference since all STL containers make deep-copies which are rather costly.

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