1

I'm making a wrapper for a SQL database and the objects I return are shared_ptr.
I'd like to support array-type access (ie row["column"] instead of row->get("column")). The objects the shared_ptr stores support array-type access, but of course the shared_ptr doesn't.
How should I do this with shared_ptrs, would I need to extend the class?

Xharze
  • 2,703
  • 2
  • 17
  • 30
user1520427
  • 1,345
  • 1
  • 15
  • 27
  • 1
    @BoBTFish: I seem to remember that operator[] must be a meber... – Emilio Garavaglia Jul 23 '12 at 08:49
  • Correct, I just stuck that there as a first thought. Now I tested it and realised it didn't work, I've deleted the suggestion. – BoBTFish Jul 23 '12 at 08:56
  • @IgorR. I guess that will be the easiest way, but I was hoping to avoid the indirection. Oh well. – user1520427 Jul 23 '12 at 09:12
  • @user1520427 besides the technical issues, I don't believe it would be a good idea. Afterall, shared_ptr is a *pointer* and this fact should be clear to those who read your code. (By the way, note that there is shared_array as well.) – Igor R. Jul 23 '12 at 09:26
  • Good point, I might just save myself some hassle and use indirection. Thanks. – user1520427 Jul 23 '12 at 10:09
  • @IgorR. That should be an answer. It is simple and expresses the intent clearly. – RedX Jul 23 '12 at 11:17

1 Answers1

2

The most obvious thing is to add an operator[] to shared_ptr. That means define your-own shared_ptr reusing std::shared_ptr and having the [] operator working the way you want.

This can be done in a quick and dirty way by deriving shared_ptr (note: shared_ptr are not polymorphic objects, so don't mix up std:: and yours in a same context, so that you can reuse their interface).

If you are a "don't derive if the destructor isn't virtual" fan, than it is up to you to embed std::shared_ptr in yourptr, and rewrite the shared_ptr interface in yourptr one, delegating the functionality you have to retain.

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
  • I was hoping to avoid rewriting the interface, but seeing as its destructor function isn't virtual I guess I don't have much choice. Out of curiosity, do you know why the std lib functions aren't virtual? Is it a performance thing? – user1520427 Jul 23 '12 at 09:07
  • Because they are not be intended for "polymorphism". The problem is that OOP fans think that derivationm is for OOP only. But to that's their fault, not of who derives. See http://stackoverflow.com/a/10478845/924727 or http://stackoverflow.com/a/11202368/924727 – Emilio Garavaglia Jul 23 '12 at 09:33