重载运算符[]时返回的栈内存地址
Address of stack memory returned when overloading operator [ ]
我在为 class 中的问题重载 [] 运算符时遇到了一些问题。这是重载函数:
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;
行。 CLion returns 以下警告:Address of stack memory associated with local variable 'temp' returned
果然,尝试使用运算符时,值returned是一个内存地址。我该如何解决这个问题?与函数的return类型有关吗?
您正在获取临时地址(位于堆栈上),这将使 returned 指针几乎立即悬空。
我强烈建议对字符串使用 std::string
,不要像使用 类 的 C 一样编写 C++。
然后return by std::string
按这里的值。糟糕的类 C 替代方案是在堆上分配字符串,并且 return 最好至少为 std::unique_ptr
。
在下面的评论后编辑:
由于需要将整数转换为字符串和 return 值,因此不能 return 临时变量,结果必须比方法更有效。基本上有两个不好的选择:
- 使
temp
静态化,这样指针仍然有效。缺点是该功能不再可重入。这样更安全,因为它不会泄漏。
const char* foo(int age){
static char temp[4];
_itoa(age, temp, 10);
return temp;
}
- Return 堆分配字符串。很大的危险是你让用户去释放它:
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
应该不需要。
我在为 class 中的问题重载 [] 运算符时遇到了一些问题。这是重载函数:
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;
行。 CLion returns 以下警告:Address of stack memory associated with local variable 'temp' returned
果然,尝试使用运算符时,值returned是一个内存地址。我该如何解决这个问题?与函数的return类型有关吗?
您正在获取临时地址(位于堆栈上),这将使 returned 指针几乎立即悬空。
我强烈建议对字符串使用 std::string
,不要像使用 类 的 C 一样编写 C++。
然后return by std::string
按这里的值。糟糕的类 C 替代方案是在堆上分配字符串,并且 return 最好至少为 std::unique_ptr
。
在下面的评论后编辑:
由于需要将整数转换为字符串和 return 值,因此不能 return 临时变量,结果必须比方法更有效。基本上有两个不好的选择:
- 使
temp
静态化,这样指针仍然有效。缺点是该功能不再可重入。这样更安全,因为它不会泄漏。
const char* foo(int age){
static char temp[4];
_itoa(age, temp, 10);
return temp;
}
- Return 堆分配字符串。很大的危险是你让用户去释放它:
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
应该不需要。