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);
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.
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.
Inside every std::string is a dynamically allocated array of char .
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With