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?
-
1@BoBTFish: I seem to remember that operator[] must be a meber...Emilio Garavaglia– Emilio Garavaglia2012-07-23 08:49:52 +00:00Commented 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.BoBTFish– BoBTFish2012-07-23 08:56:46 +00:00Commented 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.user1520427– user15204272012-07-23 09:12:58 +00:00Commented 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.)Igor R.– Igor R.2012-07-23 09:26:07 +00:00Commented Jul 23, 2012 at 9:26
-
Good point, I might just save myself some hassle and use indirection. Thanks.user1520427– user15204272012-07-23 10:09:03 +00:00Commented Jul 23, 2012 at 10:09
1 Answer
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.