[英]What's the best way to extend the scope of a variable for use in a lambda in c++?
[英]What's the best way to resolve this scope problem?
我正在用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;
}
};
make_tree()
返回的Node對象只是一個臨時對象,它將在調用該函數的表達式的末尾再次自動銷毀。 當您創建指向此類臨時對象的指針時(例如在&make_tree(depth)
,一旦臨時對象被銷毀,該指針將不再指向任何有用的東西。
您應該使用帶有new
和delete
實際動態內存分配來構建樹,以免最終無法獲得指向不再存在的對象的指針。 樹的這種構造可能應該在Node
類的構造函數中完成,然后析構函數應注意釋放已用內存所需的delete
。 例如:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.