Reputation: 879
If I have something like this:
static const wchar_t* concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
s += std::wstring(ws2);
return s.c_str();
}
It wouldn't work because the scope of s
is within the static block, so the stack contents will be popped and the memory address to s
is no longer valid. So my question is how can I do this?
Upvotes: 1
Views: 3733
Reputation: 4179
Replace your return statement with the following:
wchar_t *ret = new wchar_t[s.length()+1];
wcscpy(ret, s.c_str());
return ret;
The function as you wrote it doesn't work, because upon returning, the destructor for the local variable s is called, which frees the memory pointed to by s.c_str().
Upvotes: 2
Reputation: 81
If you want to keep the function signature, try something like:
static const wchar_t* concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
wchar_t *r;
s += std::wstring(ws2);
/*
* allocate the return value in heap (with room for the null termination)
*/
r = new wchar_t[s.length() + 1];
/*** copy ***/
s.copy(r,s.length()+1);
return r;
}
by the way (as said by others) you may return the entire s object,
Upvotes: 0
Reputation: 61508
The fact that the member function (we don't say "method" in C++) is static
doesn't matter. You can return a local variable by value. What you cannot do is return a pointer or a reference to a local variable, or to a temporary value. s.c_str()
creates a pointer either to temporary data or to part of the local wstring
. So we cannot return that. Returning s
(and adjusting the return type to match) is fine, because now we are returning by value, which (conceptually; it may be optimized) makes a copy of the local string on the stack in the return-value "slot".
Upvotes: 1
Reputation: 76745
The fact that the function is static
is irrelevant here. You could return s.c_str()
if the s
variable was static
, however this would be very weird as s
would only initialized upon the first call of the function.
My recommendation : just return a std::wstring
by value.
std::wstring concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
s += std::wstring(ws2);
return s;
}
Upvotes: 5
Reputation: 11522
Change the function to return std::wstring
instead of wchar_t*
, and return s
.
static std::wstring concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
s += std::wstring(ws2);
return s;
}
By the way, this would be equally true for non-static methods.
Upvotes: 12