[英]Address of stack memory returned when overloading operator [ ]
由於 class 中的問題,我在重載 [] 運算符時遇到了一些問題。 這是用於過載的 function:
const char* Person::operator[](const char* str)
{
if (strcmp(str, "name") == 0)
return reinterpret_cast<const char *>atoi(name);
if (strcmp(str, "age") == 0)
{
char temp[4];
_itoa(age, temp, 10);
//cout << temp;
return temp;
}
}
class 定義看起來像這樣
class Person
{
private:
const char* name;
unsigned int age;
double height;
int gradeNo;
int grades[10];
public:
Person();
Person(const char* name, int age, double height);
void addGrade(int grade);
const char* operator [] (const char* str);
operator int();
};
我遇到的問題是return temp;
來自運算符重載 function 的行。 CLion 返回以下警告: Address of stack memory associated with local variable 'temp' returned
果然,在嘗試使用操作符的時候,返回的值是一個memory地址。 我該如何解決這個問題? 是不是和function的返回類型有關?
您正在獲取一個臨時地址(位於堆棧上),這將使返回的指針幾乎立即懸空。
我強烈建議使用std::string
作為字符串,不要像 C 那樣寫 C++ 和類。
然后在這里按值通過std::string
返回。 糟糕的類似 C 的替代方法是在堆上分配字符串並返回,最好至少作為std::unique_ptr
。
由於您需要將 integer 轉換為字符串並返回值,因此您不能返回臨時變量,結果必須比方法更有效。 基本上有兩個不好的選擇:
temp
static,這樣指針保持有效。 缺點是 function 不再可重入。 這更安全,因為它不會泄漏。const char* foo(int age){
static char temp[4];
_itoa(age, temp, 10);
return temp;
}
const char* foo(int age){
char* temp = new char[256];
_itoa(age, temp, 10);
return temp;
}
我相信您的代碼中也有錯字:
return reinterpret_cast<const char *>atoi(name);
atoi
不應該在那里,對吧? 不需要reinterpret_cast
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.