简体   繁体   English

C ++ boost :: shared_ptr运算符[]详细信息

[英]C++ boost::shared_ptr operator[] details

Boost documentation says Boost文档说

Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. 从Boost 1.53版本开始,shared_ptr可用于保存指向动态分配数组的指针。

I have an simple class and using boost::shared_ptr to hold array of std::deque within it: 我有一个简单的类,并使用boost::shared_ptr在其中保存std::deque数组:

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. 这是因为语法恒定性要求对象及其成员(在这种情况下,尤其是智能指针)必须是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. 如果数组属于您的对象,则更改数组意味着更改对象,而使对象为const则意味着不更改数组。 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. 但是,在这种情况下,我不会使用shared_ptr而是使用std::vector ,因为它表示单一所有权,而shared_ptr是共享所有权-显然。 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. 另外, std::vector旨在实现语义一致性,这意味着库实现者将包含的元素强制为const向量中的const。
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. 但是,由于我不知道您的类和双端队列的上下文,并且由于您显式地使用shared_ptr ,所以意味着共享所有权, 也许您需要语义常量,也许不需要。

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 通过const引用返回也可以满足您的需要,而且还避免了不必要的临时副本,这取决于出队存储的对象数量可能非常昂贵

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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