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?

6
  • 1
    @BoBTFish: I seem to remember that operator[] must be a meber... Commented Jul 23, 2012 at 8: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. Commented Jul 23, 2012 at 8:56
  • @IgorR. I guess that will be the easiest way, but I was hoping to avoid the indirection. Oh well. Commented Jul 23, 2012 at 9: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.) Commented Jul 23, 2012 at 9:26
  • Good point, I might just save myself some hassle and use indirection. Thanks. Commented Jul 23, 2012 at 10:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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 stackoverflow.com/a/10478845/924727 or stackoverflow.com/a/11202368/924727

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.