For performance reasons I need to build a matrix of pointers to objects instead of plain objects. Whenever I require a big matrix I usually go for the Boost implementation
#include <boost/numeric/ublas/matrix.hpp>
usingnamespace boost::numeric::ublas;
matrix<CNode*> Grid(DIM_X, DIM_Y, 0);
CNode* Node_ptr = 0;
for(int i = 0; i < NUMNOD; i++)
{
// creates Node object and pointer
CNode Node;
Node_ptr = &Node;
// other operations...
Grid(n,m) = Node_ptr;
}
where n and m are obtained in some preceding code. At this point I am not sure if the Node_ptr pointers in the matrix are located in the stack or the heap. I want my pointers to live in the heap, and I also want smart pointers so I don't have to worry about possible memory leaks.
Is there a matrix-like container of smart pointers in Boost?
Line 11: Node is on the stack. Although Node is pushed on the stack each time through the loop, it is popped off the stack at line 17. Node will always occupy the location on the stack. Therefore &Node will always point to the same address.
Delete line 16 and change line 17 to:
Node_ptr = new CNode;
Don't forget to delete everything you create with new.
matrix can consist of whatever type you specify. That can be a smart pointer, although a unique_ptr (C++11) may be more appropriate here.