3

I want to start using smart pointers in my code but I don't really want to use Boost because it's so huge.

Can anyone recommend a simple, one-file smart pointer implementation?

Thanks, Boda Cydo.

2
  • You could write one yourself and become incredibly famous in the process. Jul 29, 2010 at 17:40
  • 1
    Or possibly infamous - writing smart pointers is not an exercise for the faint-hearted.
    – anon
    Jul 29, 2010 at 17:47

4 Answers 4

4

Unfortunately, smart pointers are not all that simple, so the implementation may be quite complicated. Having said that, if you are using g++ you get things like shared_ptr without having to use Boost:

#include <memory>
using namespace std;

int main() {
    shared_ptr <int> p( new int );
}

but you will have to compile with the -std=c++0x flag.

3
  • Thanks. Can you please tell me where shared_ptr is located?
    – bodacydo
    Jul 29, 2010 at 17:43
  • Perhaps it's worth pointing out to bodacydo that the c++0x flag turns on experimental support for an uncertified new C++ standard and is probably not a good idea for production code. boost is not really a hugeness issue. Just check it into your repository and use the bits of it you need. Most of it is header file only so you only compile what you need. I was initially nervous of boost till a colleague came over one day and looked at my code and informed me that half my half arsed utility code was already in boost and more reliable. Jul 29, 2010 at 17:59
  • @brad shared_ptr doesn't use any new C++0x features - but I agree that the flag turns on other things you might not want (or there again, you might).
    – anon
    Jul 29, 2010 at 18:03
3

You could upgrade to a recent-enough compiler and use what TR1 gives you. The compiler I use has included TR1 pre-releases for many years.

1

The thing is boost is just a set of header files (the majority).

So when you use things like smart pointers all you get are the smart pointers.
There is no extra cost for the things you are not using.

0

Probably this may help you: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.22. It's a short example for implementing reference counting. In case you're implementing "shared_ptr" by yourself, cases of simple pointer and array should be distinguished, like in boost.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.