Archived

This topic is now archived and is closed to further replies.

Floating

Object on the stack which allocates memory on the heap...

Recommended Posts

Hi, I was wondering about something: I used to have matrices I built like this: float matrix[4][4]; This was fine until I needed to have also matrices with different dimensions. I then wrote a matrix class and now I build my matrices with CMatrix matrix(5,8); The memory needed for that matrix is allocated with the new operator, so on the heap. This can rapidly lead to memory fragmentation, no? Could I allocate the memory needed for my matrix on the stack too (if there is a way to know for the object if it was built on the stack or heap)? How? Thanks

Share this post


Link to post
Share on other sites
Objects allocated on the stack are only good for that particular function call. It may be possible to tell if the object has been allocated with new or on the stack, but that would be a bad thing to do. Also, it indicates a poor design/implementation.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
If you want the internal representation of your matrices stack-allocated you could use template specializers to specify the sizes as such


  
template <typename T, size_t Rows, size_t Columns>
class Matrix
{
public:
...
private:
T m[Rows][Columns];
};


Then using it would be done by


Matrix<int,5,5> foo;

Share this post


Link to post
Share on other sites
If you absolutely MUST have it on the stack, templated is the way to go.

Otherwise, look into using a Pool design pattern, or use Loki''s small object allocator.

Share this post


Link to post
Share on other sites
There''s no implementation-agnostic way to tell if the memory was allocated on the stack or the heap; this is a question from one of the Effective C++ books by Scott Meyers (both excellent).

If you want to dynamically allocate things on the stack you can either use a templated form previously presented or the _alloca() function in malloc.h, which lets you allocate an non-constant number of bytes from the stack at runtime. It is very cheap (pointer subtract) and requires no cleanup, but you should do it for raw data only, not objects.

Share this post


Link to post
Share on other sites