Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return a std::string &

std::string &func(int vlu)
{
    std::string str;
    str = std::to_string(vlu) + "something";

    return str;
}

the function above is unsafe clearly.
Following is another version.

std::string &func(int vlu)
{
    return std::to_string(vlu) + "something";
}  

I have some questions:
the compiler(gcc), in the second version, doesn't give me any warning. Is it safe? I just think that compiler(or something?) will create a temporary variable to hold the return of expression std::to_string(vlu) + "something". So the second version is unsafe too. and I right?

like image 210
umbreLLaJYL Avatar asked Oct 29 '18 10:10

umbreLLaJYL


People also ask

How do I return STD strings?

Try this: std::string * sp; std::string func() { std::string s("bla"); sp = &s; return s; } int main() { std::string s = func(); if(sp == &s) std::cout << "YAY"; else std::cout << "BOO"; } -- On my compiler (VS) It prints YAY.

Can I return a string in C++?

Use the std::string func() Notation to Return String From Function in C++ Return by the value is the preferred method for returning string objects from functions. Since the std::string class has the move constructor, returning even the long strings by value is efficient.

Can you use std::string in C?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.

How do you return a character from a string in C++?

string at() in C++ std::string::at can be used to extract characters by characters from a given string. Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0).


1 Answers

No, neither program is safe. In both cases the returned reference is dangling and the behaviour of using the reference will be undefined.

The second program is also ill-formed, because it attempts to bind an lvalue reference (that is returned) to an rvalue (the temporary). The second program might be considered "less unsafe", since a compiler might choose to not compile it.

To fix the function: Don't attempt to return a reference, when the purpose is to return a new object. Return an object instead.

like image 175
eerorika Avatar answered Sep 29 '22 22:09

eerorika