Reputation: 1453
My project is in c++11, using vs2012. Right now I don't feel the need of using custom memory management but, what arrangements should I take in order to facilitate an eventual future modification?
I thought of using a macro for "new"/"new[]"/"delete"/"delete[]" and typedefs for containers and smart pointers.
What are the best practises?
Upvotes: 5
Views: 298
Reputation: 2491
From my point of view, all you have to do is basically decide on a certain convention that you will use throughout your implementation. A good template for making your architecture allocator aware is to look on how this is achieved for the STL containers and try to design you data structures like them. If you look for example on the std::vector
interface the second parameter to this container is always the Allocator type. The Allocator has to follow a certain interface that will allow easy replacing of the default allocator implementation by a custom one.
But coming back to code that you write: In a project that I work on we defined it like follows. For an object that is supposed to consume large amounts of memory we define a templated super class that allows to specify a custom allocator.
template<class AllocatedClass, typename Allocator=std::allocator<AllocatedClass>
class AbstractMyClass {
public:
static void *operator new(size_t sz){ /*...*/ }
static void operator delete(void *p){ /*...*/ }
};
Now, if you define a subclass of this you would:
class MyClass : public AbstractMyClass<MyClass> {
};
Thus the new object MyClass
will use the specified allocator of the parent class. If you now implement you own allocator you can simply replace either the default template parameter in the super class or you can specify it explicitly in your sub-class.
Using this approach you are more or less safe in using a custom allocator at a later point in time.
Upvotes: 2
Reputation: 42924
In modern C++ code, new/new[]/delete/delete[]
should be used rarely.
In fact, they are leak-prone and exception unsafe; moreover, in general, owning raw pointers should be confined in RAII classes, with proper destructors for cleanup.
You should instead use STL containers like std::vector
(instead of new[]/delete[]
), and smart pointers like shared_ptr
, unique_ptr
, etc.
In case of STL containers, they do support custom memory allocation. For an example of a skeleton custom allocator, see the Mallocator (you can customize it with special allocation techniques like pool memory allocation).
Upvotes: 1