以下安全性如何,沒有顯式強制轉換或調用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