我正在阅读Bjarne Stroustrup 的第3版C++编程语言并尝试完成所有练习.我不确定如何从第6.6节开始练习13,所以我想我会转向Stack Overflow以获得一些洞察力.这是问题的描述:
编写一个函数cat(),它接受两个C风格的字符串参数,并返回一个字符串,该字符串是参数的串联.使用new查找结果的商店.
这是我到目前为止的代码,带有问号,我不知道该怎么做:
? cat(char first[], char second[])
{
char current = '';
int i = 0;
while (current != '\0')
{
current = first[i];
// somehow append current to whatever will eventually be returned
i++;
}
current = '';
i = 0;
while (current != '\0')
{
current = second[i];
// somehow append current to whatever will eventually be returned
i++;
}
return ?
}
int main(int argc, char* argv[])
{
char first[] = "Hello, ";
char second[] = "World!";
? = cat(first, second);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是我的问题:
std::string* result = new std::string;或者我应该使用new来创建另一个C风格的字符串?\n\n\n如何使用new来查找商店?我是否期望做类似的事情
\nstd::string* result = new std::string;或者我应该使用新的以某种方式创建另一个 C 风格字符串?
后者; 该方法采用 C 样式字符串,文本中没有任何内容表明它应该返回任何其他内容。因此该函数的原型应该是char* cat(char const*, char const*). 当然这不是\xe2\x80\x99d 通常编写函数的方式;手动内存管理在现代 C++ 中是完全禁忌的,因为它\xe2\x80\x99s 很容易出错。
\n\n\n虽然问题没有提到使用 delete 来释放内存,但我知道我应该这样做,因为我将使用 new 来分配内存。我应该在返回之前在 main 末尾删除吗?
\n
在这个练习中,是的。在现实世界中,不:就像我上面说的,这完全是禁忌。实际上,您将返回 astd::string并且不使用 分配内存new。如果您发现自己手动分配内存(并假设它\xe2\x80\x99s有充分的理由),则\xe2\x80\x99d将该内存不是放在原始指针中,而是放在智能指针\xe2\x80\x93std::unique_ptr或std::shared_ptr.