开发者

C++: Can you return the value of a local variable from a static method?

开发者 https://www.devze.com 2023-01-29 15:25 出处:网络
If i have something like this: static const wchar_t* concatenate(const wchar_t* ws1, const wchar_t开发者_Python百科* ws2) {

If i have something like this:

static const wchar_t* concatenate(const wchar_t* ws1, const wchar_t开发者_Python百科* 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?

Thanks


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.


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;
}


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().


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".


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,

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号