繁体   English   中英

将char数组作为std:string返回

[英]Returning char array as std:string

以下是否安全,没有显式强制转换或调用std :: string构造函数? 如果不安全,为什么不呢?

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

   return buf;
}

是。 那很好。 调用者将获得本地缓冲区的副本,因为std::string将从此本地缓冲区中进行深层复制!

编辑:我假设buf是以null结尾的字符串!

是的,没关系,请记住在C ++中,将会发生一个隐式构造函数来创建返回对象,并且可以使用字符数组构造一个字符串。 在C ++中,如果不想创建副本,则必须通过引用显式返回。

实际上,它是安全的。 但那只是因为你正在初始化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

安全(对于空终止缓冲区)但不容易阅读,考虑将最后一行更改为

return std::string(buf);

编辑:请参阅karlphillip的安全性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM