[英]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.