2011-03-16 42 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。