zeb*_*und 1 c++ memory heap stack pointers
这可能吗?根据我想要完成的事情,似乎并非如此.
功能
static std::string str_repeat(std::string * str, int num_times) {
std::string * str_rep = new std::string;
for (int n = 1; n <= num_times; n++) {
str_rep = str_rep + str;
}
std::string ret = *str_rep; //error
delete str;
delete str_rep;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
更新
对不起,我没有首先发布错误,因为我认为这是一个普遍的C++问题,我做错了.这里是.
error: invalid operands of types ‘std::string* {aka std::basic_string<char>*}’ and ‘std::string* {aka std::basic_string<char>*}’ to binary ‘operator+’
Run Code Online (Sandbox Code Playgroud)
首先,如果你曾经说过new std::string那么你可能做错了什么.这段代码中不应该包含任何指针(并且str_rep = str_rep + str在代码中是指针算法,而不是追加,这就是取消引用结果失败的原因).
std::string str_repeat(const std::string& str, int num_times) {
std::string ret;
for (int n = 0; n < num_times; ++n) {
ret += str;
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)