shared_ptr<>
에 대한 경험이없는 경우 다음이 적합한 유즈 케이스인지 궁금하고 shared_ptr<>
을 사용자에게 반환하는 것이 좋습니다.shared_ptr의 적절한 사용?
노드 사이에 여러 개의 연결이있는 구조의 그래프가 있습니다. 그래프를 탐색하는 동안 각 노드에는 연결된 노드에서 계산 된 값이 할당되며 사용자가 값에 쉽게 액세스 할 수 있기를 원합니다. 이런 모든 것은 외모 (강하게 간체) :
class Pool;
class Node {
public:
typedef std::tr1::shared_ptr<Node> Ptr;
...
void compute_dependencies() {
...
// calls Pool to get a new Node instance
dependencies_.push_back(Pool::create_node(...));
...
}
// evaluate the current node
void evaluate() { /* use dependencies_ */ };
double value() const { if(evaluated) return value_; };
private:
std::vector<Node::Ptr> dependencies_; // vector<Node*> better?
dbl value_;
}
// Pool creates and owns all nodes
class Pool {
public:
static const Node::Ptr create_node(...); // create a new node
void traverse_and_evaluate();
private:
std::vector<Node::Ptr> allnodes; // appropriately sorted to ensure
// dependencies are evaluated
...
}
사용자 전화 :
Pool pool();
Node::Ptr node1 = Pool::create_node(...);
Node::Ptr node2 = Pool::create_node(...);
....
pool.traverse_and_evaluate();
// ready to read out the now populated values
cout << node1->value() << " " << node2->value() << ...
이 사용자가 직접 얻을 그는 대한 관심 노드에 액세스 할 수 있다는 이점이있다 (의존성은 종종 시시한). 하지만 이것이 좋은 생각인지 100 % 확신 할 수는 없습니다.
입력 해 주셔서 감사합니다.
편집 : 순환 종속성이 없습니다.
이 질문과 답변은 다소 관련성이 있습니다. http://stackoverflow.com/questions/5629592/resource-leak-during-object-creation-c/ – Anton