简体   繁体   中英

how to return std::string from a function in c++

I'm trying to return a string from a function that does some processing.

I've tried returning it as an rvalue reference and also as an lvalue reference. didn't work:(.

processing function:

std::string processingFunction()
{
    std::string str = "";
    //processing...
    strftime(&str[0], MAX_LENGTH, DATE_FORMAT, tm_STRUCT_ADRRESS);
    return str;
}

use of the function:

std::string temp = processingFunction();
if(temp.empty())
{
    //stuff
}

When debugging (in VS 2019), I can see the value of temp in the Watch, but temp.empty() always returns 1 . Even if I can see that the value is present.

here is a screenshot for tl;dr: m_bucket_function is the processing function

You define a std::string object and set it to "" (the empty string).

You then use strftime() to copy, as a C-style string, a representation of some time to memory starting at &str[0] .

The expression &str[0] (where str is a std::string ) does give you access to the initial byte of the data managed by the str::string object -- but it doesn't allocate memory to hold the new value, and it doesn't update the std::string object's internal data (including the length of the string it represents). Your call to strftime() is likely to clobber unallocated memory (undefined behavior).

You need to use strftime() to copy data into a char array, and then copy that data into your str . std::string 's assignment operator will then take care of updating the metadata and allocating memory as needed.

There's no problem with returning a std::string by value, as you're doing.

temp.empty() always returns 1

just means the string is empty.

Now that you've posted more code and as @SkyZip comments, the problem lies in:

strftime(&str[0], ...

this gets strftime to overwrite memory by passing it the address of your string.

If you really have to use strftime you can do it like so:

std::string processingFunction()
{
    char buff[MAX_LENGTH];
    strftime(buff, MAX_LENGTH, DATE_FORMAT, tm_STRUCT_ADRRESS);
    //processing...
    return std::string(buff);
}



And as @Keith said, you are working with objects here. Not just plain old C data types.


Just for reference, here is a similar question: Current date and time as string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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