我可以在C ++中执行以下操作吗?
std::string a = "";
a = "hello";
a += ", good sir";
//use a in the program
a = "";
a = "bye";
a += " to you";
//use it for something else
如果这不是合法操作,是否会引起内存问题?最后一点对我很重要,因为我有其中一些,而且我正试图弄清它们的来源。
答案 0 :(得分:1)
是的,您可以一对一地重复使用同一变量以用于多种用途。但是实际上我不推荐您,如果您仅使用一个变量来多次使用,该程序就会有些混乱。
类std::string
自动分配所需的字节内存以存储字符串文字,并在更改字符串时重新分配。
例如:
#include <iostream>
std::string a = "hello"; // global a, allocates the required memory
int main(void) {
std::string a = "world"; // local a, allocates the required memory
::a = "hello changed"; // accessing global a (reallocates memory)
std::cout << a << std::endl; // local a
}
不过,使用两次或更多次没有问题。但是请注意您的代码,并确保在第二次或第n次使用之前已将其正确清除。
答案 1 :(得分:0)
那应该很好,不用担心
std :: string根据需要分配内存