Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Return std::string reference from stack memory

I will start by saying I've read this topic: C++ Return reference / stack memory. But there, the question was with an std::vector<int> as object-type. But I though the behavior of std::string was different. Wasn't this class especially made for using strings without having to worry about memory-leaks and wrong usage of memory?

So, I already know this is wrong:

std::vector<t> &function()
{
    vector<t> v;
    return v;
}

But is this wrong as well?

std::string &function()
{
    string s = "Faz";
    s += "Far";
    s += "Boo";
    return s;
}

Thanks


Extra question (EDIT): So, am I correct when I say returning (by value) an std::string doesn't copy the char sequence, only a pointer to the char * array and an t_size for the length?

If this statement is correct, is this the valid way to create a deep copy of a string (to avoid replacing will alter the string)?

string orig = "Baz";
string copy = string(orig);
like image 731
Martijn Courteaux Avatar asked Jun 17 '11 16:06

Martijn Courteaux


People also ask

How do you return a string reference 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.

Is std::string on stack or heap?

On Windows platform, in C++, with std::string, string size less than around 14 char or so (known as small string) is stored in stack with almost no overhead, whereas string size above is stored in heap with overhead.

Is std::string dynamically allocated?

Inside every std::string is a dynamically allocated array of char .

How are strings stored in memory C++?

@user1145902: They are stored in memory like in an array, but that memory is not allocated in the stack (or wherever the string object is), but rather in a dynamically allocated buffer.


1 Answers

It doesn't matter what the type is; this pattern is always completely, 100% wrong for any object type T:

T& f() {
    T x;
    return x;
}   // x is destroyed here and the returned reference is thus unusable

If you return a reference from a function, you must ensure that the object to which it refers will still exist after the function returns. Since objects with automatic storage duration are destroyed at the end of the block in which they are declared, they are guaranteed not to exist after the function returns.

like image 173
James McNellis Avatar answered Nov 11 '22 17:11

James McNellis