如果我有这样的事情:
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();
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为's'的范围在静态块内,因此堆栈内容将被弹出,而's'的内存地址不再有效,所以我的问题是我该怎么做?
谢谢
Dan*_*lau 12
将函数更改为return std::wstring
而不是wchar_t*
,并返回s
.
static std::wstring concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
s += std::wstring(ws2);
return s;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,对于非静态方法也是如此.
这个功能的事实static
与此无关.如果变量是,你可以返回,但是这将是非常奇怪的,因为只有在第一次调用函数时才会初始化.s.c_str()
s
static
s
我的建议:只返回一个std::wstring
值.
std::wstring concatenate(const wchar_t* ws1, const wchar_t* ws2) {
std::wstring s(ws1);
s += std::wstring(ws2);
return s;
}
Run Code Online (Sandbox Code Playgroud)