我正在將 Raylib GUI 框架用于顯示 Collat??z 猜想迭代中的所有節點的專案。在我的程式中,我有一個Node物件類,它只是一個帶有標記數字的圓圈。text但是,我的方法中的變數draw有問題;C26815: The pointer is dangling because it points at a temporary instance which was destroyed. 我是 C 新手,目前沒有任何書籍可以教我,因此我不完全確定“懸空”指標是什么或它的含義,但我相當確定這是原因我無法在我的節點上顯示任何文本。這是我的Node課:
class Node {
private:
int x;
int y;
int value;
int radius;
public:
Vector2 get_pos() {
return Vector2{ (float)x, (float)-value * 25 };
}
void set_radius(int newRadius) {
radius = newRadius;
}
void set_value(int newValue) {
value = newValue;
}
void set_x(int newX) {
x = newX;
}
void set_y(int newY) {
y = newY;
}
void draw() {
if (value) {
const char* text = std::to_string(value).c_str();
Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f);
Vector2 pos = get_pos();
DrawCircle(pos.x, pos.y, radius, WHITE);
DrawText(text, pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK);
}
}
};
任何有關正在發生的事情的幫助或解釋將不勝感激。
編輯:其他人在其他問題上也有類似的問題,但沒有一個答案對我有意義或不適用于我的情況。
uj5u.com熱心網友回復:
在這一行
const char* text = std::to_string(value).c_str();
您正在呼叫c_str()which 回傳指向由 . 回傳的臨時緩沖區的指標std::to_string(value)。此臨時生命周期在此行的末尾結束。從回傳的指標c_str僅在字串仍然存在時才有效。
如果DrawText復制字串(而不僅僅是復制您傳遞的指標),您可以通過以下方式修復它
std::string text = std::to_string(value);
Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f);
Vector2 pos = get_pos();
DrawCircle(pos.x, pos.y, radius, WHITE);
DrawText(text.c_str(), pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436692.html
