我现正进行一项现有的大型工程,基本上:
目前,子程序使用智能指针存储,主要是为了避免在从文件读取和图形的用户版本构建图形时进行深度复制。
由于智能指针(std::shared_ptr)不传播一致性,因此我有以下选项:
我知道,在c++11和move语义时代,仅使用智能指针来避免树操作期间的深拷贝并不是实现这一点的好方法。用move语义重写所有代码可能有一天会完成,但这是一项相当大的工作。
在您看来,实现该模式的最佳方式是什么,而不使用移动语义重写所有这些呢?我曾经想过用std::shared_ptr包装来传播恒定性,还有其他的想法吗?
谢谢!
发布于 2014-10-05 02:56:28
我将使用选项3,但将子元素存储在基类或组合对象中的私有成员变量中。
只允许通过增强const正确性的getter访问子节点。
const getter返回指向-const的原始指针。非压缩器返回原始指针或共享指针。
类似于:
#include <iostream>
#include <memory>
#include <vector>
template<class Child>
class Parent {
private:
std::vector<std::unique_ptr<Child>> children_;
protected:
~Parent() = default;
public:
const Child* getChild(size_t child_number) const {
return children_.at(child_number).get();
}
Child* getChild(size_t child_number) {
return children_.at(child_number).get();
}
size_t getNumberOfChildren() const {
return children_.size();
}
void addChild(std::unique_ptr<Child> child) {
children_.emplace_back(std::move(child));
}
};
struct Node : Parent<Node> {
private:
std::string name_;
public:
Node(std::string name) : name_(std::move(name)) {}
void print() const { std::cout << "Node: " << name_ << "\n";}
void setName(const std::string& name) { name_ = name; }
void wrong() const {
//children_[0]->setName("Wrong"); // Not allowed
//getChild(0)->setName("Wrong"); // Not allowed
}
};
void printRecursive(const Node* node) {
if (node) {
node->print();
for (size_t i=0; i!=node->getNumberOfChildren(); ++i)
printRecursive(node->getChild(i));
}
}
int main() {
// Initialization
Node root("Root");
root.addChild(std::make_unique<Node>("Child 1"));
root.addChild(std::make_unique<Node>("Child 2"));
// "Computation" with pointer-to-const
const Node* root_ptr = &root;
printRecursive(root_ptr);
}现场演示。
现场演示-使用构图。
在我的示例中,我使用了unique_ptr而不是shared_ptr,因为我可以使用,但是您可能有充分的理由使用shared_ptr。
https://stackoverflow.com/questions/26179399
复制相似问题