I'm starting to write a library and considering its interface. Previous libraries I've written all use raw pointers (both internally and in its interface), and now I want to try the smart pointer library that comes with VS2010.
Please help :)
In modern C++ programming, the Standard Library includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe.
So, a smart pointer is only needed, when you use new or other means of dynamic memory allocation. In my opinion, you should prefer to allocate variables on the stack, so when refactoring code (to C++11), you should always ask yourself, if this new is needed, or could be replaced with an object on the stack.
Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) is destroyed, for example because it goes out of scope, the pointed object is destroyed too.
A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.
It is imposable to answer those question without understanding a lot more about your design principles and how you expect the library to be used.
So I can only answer based on my experience and how I like my libraries to be used.
For Example:
#if defined(MY_PROJ_SHARED_PTR_FROM_BOOST)
#include <boost/shared_ptr.hpp>
#define MY_PROJ_SHARED_PTR_NAMESPACE boost
#elif defined(MY_PROJ_SHARED_PTR_FROM_STD)
#include <memory>
#define MY_PROJ_SHARED_PTR_NAMESPACE std
#elif defined(MY_PROJ_SHARED_PTR_FROM_TR1)
#include <tr1/memory>
#define MY_PROJ_SHARED_PTR_NAMESPACE std::tr1
#else
#error "MY_PROJ_SHARED_PTR_FROM_<XXX> not defined correctly"
#endif
namespace X
{
using ::MY_PROJ_SHARED_PTR_NAMESPACE::shared_ptr;
}
int main()
{
X::shared_ptr<int> data;
}
I am sure there are other ways to do this.
But it is late.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With