Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning char array as std:string

Tags:

c++

Is the following safe as is, without an explicit cast or call to std::string constructor? If not safe, why not?

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

   return buf;
}
like image 678
CodeLizard Avatar asked Mar 16 '11 16:03

CodeLizard


3 Answers

Yes. That is perfectly fine. The caller will get a copy of the local buffer, because std::string would make a deep-copy out of this local buffer!

EDIT: I'm assuming the buf is null-terminated string!

like image 104
Nawaz Avatar answered Nov 15 '22 18:11

Nawaz


Yes that is fine, remember in C++, what will happen is an implicit constructor will be called to create the return object, and a string can be constructed with a character array. In C++ you have to explicitly return by reference if you don't want a copy created.

like image 31
titania424 Avatar answered Nov 15 '22 17:11

titania424


Actually, it is safe. But that's just because you are initializing the char array like that, which is extremely important. Consider the following code:

#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;
}

Outputs:

empty_str size is: 0
str size is: 6
str: qwerty
like image 29
karlphillip Avatar answered Nov 15 '22 18:11

karlphillip