Alf P. Steinbach wrote:
* James Kanze:
>On Feb 28, 7:25 pm, Phil Endecott <spam_from_usen et_0...@chezphi l.org>
wrote:
>>Sebastian Nibisz wrote:
or
>>>>struct node
{ boost::shared_p tr<nodenext;
};
>>>{
for (int x = 0; x < 1000000; ++x)
{
n = n->next = shared_ptr<node >(new node);
}
} // <- STACK OVERFLOW
>>Why?
You're kidding us, right?
....
>>
It's really pretty rare that you can recurse 1000000 times
without the stack overflowing.
Huh?
I'm not sure it's obvious until you're been looking at it for a few
minutes, but given a program like the following:
#include <tr1/memory>
using std::tr1::share d_ptr;
struct node {
shared_ptr<node next;
};
int main() {
shared_ptr<node root(new node);
shared_ptr<node n(root);
for (int x = 0; x < 1000000; ++x) {
n = n->next = shared_ptr<node >(new node);
}
}
When the "root" shared_ptr goes out of scope, the first node's reference
count goes to zero. root's destructor therefore deletes the first node,
causing the destructor of root->next to be invoked. That destructor
sees the reference count of the second node become zero, and so deletes
the second node, causing root->next->next to be invoked. And so on...
A better approach, IMHO, would be to let a factory allocate the nodes,
preferably as elements of a std::list<node> . The factory's destructor
(the list's, really) can make sure the memory is freed.