以下安全性如何,没有显式强制转换或调用std :: string构造函数?如果不安全,为什么不呢?返回char数组作为std:string
std:string myfunc()
{
char buf[128] = "";
// put something into buf or not base on logic.
return buf;
}
以下安全性如何,没有显式强制转换或调用std :: string构造函数?如果不安全,为什么不呢?返回char数组作为std:string
std:string myfunc()
{
char buf[128] = "";
// put something into buf or not base on logic.
return buf;
}
是的,这很好,记住在C++中,会发生什么是隐式构造函数将被调用来创建返回对象,并且可以使用字符数组构造字符串。在C++中,如果您不想创建副本,则必须通过引用显式返回。
不安全,除非buf肯定是空的终止! – T33C 2011-03-16 16:52:00
它是安全的,正如下面的@karlphillip所描述的,因为char buf [128] =“”;是一个初始化,它会将buf设置为指向一个以null结尾的空字符串,而不是在数组中设置单个字符。 – titania424 2011-03-16 17:08:44
其实它很安全。但那只是因为你正在初始化char array
那样,这是极其重要的。请看下面的代码:
#include <string.h>
#include <iostream>
#include <string>
std::string alloc_string(bool fill)
{
char buf[128] = ""; // Proper declaration/initialization of the array.
if (fill)
{
strcpy(buf, "qwerty");
}
return buf;
}
int main()
{
std::string empty_str = alloc_string(false);
std::cout << "empty_str size is: " << empty_str.size() << std::endl;
std::string str = alloc_string(true);
std::cout << "str size is: " << str.size() << std::endl;
std::cout << "str: " << str << std::endl;
}
输出:
empty_str size is: 0
str size is: 6
str: qwerty
如果你忘记初始化数组,你肯定会破坏代码,因为那块内存上可能会有垃圾。试试看,你可能会注意到'empty_str'不再是空的,即使你没有复制任何内容。 – karlphillip 2011-03-16 17:16:47
安全(对空终止缓冲区),但不容易阅读,考虑到最后一行改为
return std::string(buf);
编辑:请参阅关于安全的karlphillip。
实际上问题的标题不正确。你将char数组作为std :: string返回。 – Benoit 2011-03-16 16:47:42
编辑问题标题。 – 2011-03-16 16:50:08