【问题标题】:What's the best way to resolve this scope problem?解决此范围问题的最佳方法是什么?
【发布时间】:2010-05-02 13:54:53
【问题描述】:

我正在用 python 编写一个程序,该程序使用遗传技术来优化表达式。

构造和评估表达式树是时间消耗,因为它可能发生

每次运行数十亿次。所以我想我会学习足够的 c++ 来编写它,然后将其合并

在 python 中使用 cython 或 ctypes。

我在 stackoverflow 上做了一些搜索,学到了很多东西。

此代码编译,但指针悬空。

我试过 this_node = new Node(... 。它似乎没有用。而且我完全不确定我会怎么做

删除所有引用,因为会有数百个。

我想使用保持在范围内的变量,但也许这不是 c++ 的方式。

什么是c++方式?

    class Node
    {
    public:
        char *cargo;
        int depth;
        Node *left;
        Node *right;
    }


  Node make_tree(int depth)
    {
        depth--;   
        if(depth <= 0)
        {
            Node tthis_node("value",depth,NULL,NULL);
            return tthis_node;
        }
        else
        {
            Node this_node("operator" depth, &make_tree(depth), &make_tree(depth));
            return this_node;
        }

    };

【问题讨论】:

  • 使用复制粘贴的方式发布真实代码。
  • 我确实复制并粘贴了真实代码,但我确实从值和运算符数组中删除了一些随机选择的“货物”值。它看起来不正确吗?
  • 是的,它有多个错误 - 它肯定不会编译。

标签: c++ scope


【解决方案1】:

make_tree() 返回的 Node 对象只是一个临时对象,它会在调用函数的表达式结束时再次自动销毁。当您创建指向此类临时对象的指针时,例如在&amp;make_tree(depth) 中,一旦临时对象被销毁,该指针将不再指向任何有用的东西。

您应该使用真正的动态内存分配与newdelete 来构建树,这样您就不会得到指向不再存在的对象的指针。可能树的这种构造应该在Node 类的构造函数中完成,然后析构函数应该处理释放已用内存所需的deletes。例如:

class Node {
public:
    const char *cargo;
    int depth;
    Node *left;
    Node *right;

    Node(int a_depth);
    ~Node();
};

// constructor
Node::Node(int a_depth) {
    depth = a_depth;
    a_depth--;   
    if(a_depth <= 0)
    {
        cargo = "value";
        left = NULL;
        right = NULL;
    }
    else
    {
        cargo = "operator";
        left = new Node(a_depth);
        right = new Node(a_depth);
    }
}

// destructor
Node::~Node() {
    delete left;
    delete right;
}

【讨论】:

    【解决方案2】:

    C++ 方法是使用smart pointers

    在这里,您将返回本地对象的副本,制作临时对象。一旦 make_node 调用完成,该对象将不再存在,使您的指针悬空。 所以不要那样做。

    使用smart pointers 来允许节点在未引用后被释放。

    【讨论】:

    • 我会说“可以忽略不计”,它消耗的内存多于速度。在速度大小上,它几乎就像一个原始指针(假设 memver 函数调用是内联的)。但只需从 boost::shared_ptr 文档中查看该文档:boost.org/doc/libs/1_42_0/libs/smart_ptr/smarttests.htm
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多