简体   繁体   中英

C++ boost::shared_ptr operator[] details

Boost documentation says

Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array.

I have an simple class and using boost::shared_ptr to hold array of std::deque within it:

boost::shared_ptr<std::deque<uint32_t> []> someArray;

I would like to have a method to return specified deque from array for read only:

std::deque<uint32_t> MyClass::myMethod(boost::uint32_t arrayIndex) const{            
        return someArray[arrayIndex];
}

Doesn't this approach violate object's constancy?

Doesn't this approach violate object's constancy?

No. Yes. Maybe. It obviously does not affect syntactic constancy, since the compiler does not complain. This is because syntactic constancy requires the object and its members, in this case especially the smart pointer, to be const. It does not require the pointee (ie the array of deques) to be const.
The semantic constancy is another thing. If the array belongs to your object, changing the array means changing the object, and having the object const means not changing the array. It's up to you to enforce semantic constness that is not syntactic constness. However, in such a case I would not use a shared_ptr but a std::vector , because that's expressing single ownership, while shared_ptr is shared ownership - obviously. In addition, std::vector is designed to enforce semantic constancy, meaning the library implementors enforced the contained elements to be const in a const vector.
However, since I don't know the context of your class and the deque array, and since you use shared_ptr wich explicitly means shared ownership, maybe you need semantic constness, maybe not.

But since you said you want a read-only access and you return by value, that access won't change the array contents, sou you might be well. Returning by const reference might do what you need too, plus it avoids unnecessary temporary copies wich might be quite expensive depending on how many objects the dequeues store

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