我的大学教授最近给了我们一项任务,要实现我们自己的智能指针类。在他用于复制字符串的样板代码中,我发现了这段漂亮的语法糖:
while (*sea++ = *river++);// C Sting copy
我进一步研究了这段代码,发现它与 strcpy.c 中的代码完全相同,并在以下 stackoverflow 问题中进一步解释了它的工作原理: How does “while(*s++ = *t++)” copy a string?
当我尝试在下面的代码中使用这种语法糖时,结果产生了垃圾并删除了存储在“river”中的字符串:
#include<iostream>
#include<cstring>
using namespace std;
void main()
{
const char *river = "water";// a 5 character string + NULL terminator
char *sea = new char[6];
while (*sea++ = *river++);
cout << "Sea contains: " << sea << endl;
cout << "River contains: " << river << endl;
}
结果:
我知道我可以使用以下代码简单地实现所需的结果:
int i = 0;
while (i<6)
{
sea[i] = river[i];
i++;
}
但这不是我想要的答案。我想知道我的 while 循环的实现或我的 char 指针的实例化有什么问题吗?
最佳答案
你正在显示垃圾,因为当你去显示它们时你的指针指向垃圾。您在循环时推进指针,但在显示数据时需要使用原始指针。
此外,您还存在内存泄漏,因为您没有释放 char[]
缓冲区。
试试这个:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char *river = "water";// a 5 character string + NULL terminator
char *sea = new char[6];
const char *p_river = river;
char *p_sea = sea;
while (*p_sea++ = *p_river++);
cout << "Sea contains: " << sea << endl;
cout << "River contains: " << river << endl;
delete [] sea;
return 0;
}
关于c++ - 为什么 "while (*sea++ = *river++);"没有正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759921/