C ++:你可以从静态方法返回局部变量的值吗? [英] C++: Can you return the value of a local variable from a static method?

查看:121
本文介绍了C ++:你可以从静态方法返回局部变量的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的:

  static const wchar_t * concatenate(const wchar_t * ws1,const wchar_t * ws2) {
std :: wstring s(w​​s1);
s + = std :: wstring(ws2);
return s.c_str();
}

它不会工作,因为's'的范围在静态块,所以栈内容将被弹出,内存地址为's'不再有效,所以我的问题是我该怎么做?



谢谢

解决方案

更改函数以返回 std :: wstring 而不是 wchar_t * ,并返回 s

  static std :: wstring concatenate(const wchar_t * ws1,const wchar_t * ws2){
std :: wstring s(w​​s1);
s + = std :: wstring(ws2);
return s;
}

顺便说一下,这对于非静态方法同样如此。 / p>

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?

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.

这篇关于C ++:你可以从静态方法返回局部变量的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆