简体   繁体   中英

Indexing operator of an object owned by unique_ptr

I am working on a c++ project. I need to put into a std::vector different classes. I found ( Objects of different classes in a single vector? ) that it is possible to do this by creating classes with a common type and then putting pointers to the vector. In this case I could cast the pointers to the type I need. This is clear to me.

It is also mentioned that in principle it is possible to use not just pointers but smart_pointers, ie std::vector<std::unique_ptr<TMyClass>> . And this is where my problems start. TMyClass has the indexing operator ( operator[] ).

Lets say I have std::vector<std::unique_ptr<TMyClass>> A . I try to access an element of the TMyClass object like this A[0][0] or A[0].get()[0] or (A[0])[0] but when I compile I get an error:

[bcc64 Error] type 'value_type' (aka 'std::unique_ptr<.....>') does not provide a subscript operator

How can I tell the compiler that the second index is related to TMyClass object and not to the unique_ptr ? I would highly appreciate if somebody explains me how to access elements in this case.

You need to extract pointer first

A[0]  //type: std::unique_ptr<TMyClass>&

Then extract object from that pointer (pointee)

*A[0] //type: TMyClass&

And then you can use your overloaded operators on this object

(*A[0])[0] 

Pointers must be dereferenced. So, I would guess (*A[0])[0] or A[0]->[0] . Not nice looking, but that's pointers for you

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