I am using shared_ptrs extensively in my production code mainly to reduce complexity and maintenance and it generally is working fine. I have, however, written a parser for a complex meta-grammar that leaves shared objects upon exit. One of the culprits is caused by recursivity. Since the parsing code is complex in itself, I want to re-use it each time I descend to the next level. Consequently, I save off the current element in its parent's element while doing descendent parsing. But this causes the problem of too many remaining strong refs. I have experimented a good bit with weak vs strong storing and the TreeVect uses weak_ptrs, but the parent assignment problem persists:
#include "stdafx.h"
#include <memory>
#include <vector>
struct Tree;
typedef std::weak_ptr< Tree > TreeWptr;
typedef std::shared_ptr< Tree > TreeSptr;
typedef std::vector< TreeWptr > TreeVect;
struct Tree
{
TreeVect treeVect;
TreeSptr parent;
};
struct Element1 : public Tree
{
};
struct Element2 : public Tree
{
};
int main()
{
TreeSptr element1 = std::make_shared< Element1 >();
TreeSptr element2 = std::make_shared< Element2 >();
element2->parent = element1; // illustrates recursive case. ERROR: Adds extra strong ref to element1
element2->parent->treeVect.push_back( element2 );
return 0;
}
Aucun commentaire:
Enregistrer un commentaire