2011-03-16 80 views
11

以下安全性如何,沒有顯式強制轉換或調用std :: string構造函數?如果不安全,爲什麼不呢?返回char數組作爲std:string

std:string myfunc() 
{ 
    char buf[128] = ""; 
    // put something into buf or not base on logic. 

    return buf; 
} 
+0

實際上問題的標題不正確。你將char數組作爲std :: string返回。 – Benoit 2011-03-16 16:47:42

+0

編輯問題標題。 – 2011-03-16 16:50:08

回答

9

是的。這很好。調用者將獲得本地緩衝區的副本,因爲std::string會從此本地緩衝區中創建一個深層副本!

編輯:我假設buf是空終止的字符串!

+0

除非buf被終止,否則不安全! – T33C 2011-03-16 16:51:40

+0

@ T33C:正確。我添加了這個基本假設! – Nawaz 2011-03-16 16:54:31

+0

這是不好的編程習慣。而是應該確保回報是安全的。如果buf稍後被修改,則問題中的代碼不能確保這一點。 – T33C 2011-03-18 15:08:34

4

是的,這很好,記住在C++中,會發生什麼是隱式構造函數將被調用來創建返回對象,並且可以使用字符數組構造字符串。在C++中,如果您不想創建副本,則必須通過引用顯式返回。

+0

不安全,除非buf肯定是空的終止! – T33C 2011-03-16 16:52:00

+1

它是安全的,正如下面的@karlphillip所描述的,因爲char buf [128] =「」;是一個初始化,它會將buf設置爲指向一個以null結尾的空字符串,而不是在數組中設置單個字符。 – titania424 2011-03-16 17:08:44

3

其實它很安全。但那只是因爲你正在初始化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 
+1

如果你忘記初始化數組,你肯定會破壞代碼,因爲那塊內存上可能會有垃圾。試試看,你可能會注意到'empty_str'不再是空的,即使你沒有複製任何內容。 – karlphillip 2011-03-16 17:16:47

0

安全(對空終止緩衝區),但不容易閱讀,考慮到最後一行改爲

return std::string(buf); 

編輯:請參閱關於安全的karlphillip。