【发布时间】:2015-11-04 08:02:35
【问题描述】:
右值是新的,所以我对此有些怀疑......
VS2013 给出
warning C4172: returning address of local variable or temporary
对于这一行
return (std::wstring&&) (*(std::wstring*)v);
这段代码(如下)是否不可移植和/或在任何地方都有未定义的行为?如果有 - 在哪里以及为什么?难道我做错了什么? 或者这只是 VS2013 编译器的误报警告,在这种特殊情况下我应该把 pragma 忽略它?
temp_value_t 旨在用作级联调用的容器:
[输入值] -> 调用 virtual_func1(temp_value_t) -> 调用 virtual_func2(temp_value_t) -> ... -> 调用 virtual_funcLAST(temp_value_t)
而且 funcLAST 实现知道 temp_value_t 是真正的右值还是左值,所以 funcLAST 知道应该使用哪个函数。
#include "stdafx.h"
class temp_value_t
{
private:
intptr_t v;
public:
temp_value_t(const std::wstring& s)
{
v = (intptr_t)&s;
};
temp_value_t(std::wstring&& s)
{
v = (intptr_t)&s;
};
std::wstring&& get_as_temp()
{
return (std::wstring&&) (*(std::wstring*)v);
};
const std::wstring& get_as_const()
{
return (const std::wstring&) (*(std::wstring*)v);
};
};
void test(temp_value_t v, bool is_param_const)
{
std::wstring s;
if(is_param_const)
s = v.get_as_const();
else
s = v.get_as_temp();
std::wcout << L"Inner = '" << s << L"'\n";
};
int _tmain(int argc, _TCHAR* argv[])
{
{
std::wcout << L"Test with temp:\n";
std::wstring s(L"abc");
test(s, false);
std::wcout << L"Outer = '" << s << L"'\n";
}
std::wcout << L"\n\n";
{
std::wcout << L"Test with const:\n";
std::wstring s(L"abc");
test(s, true);
std::wcout << L"Outer = '" << s << L"'\n";
}
return 0;
}
/*
VS2013 results:
Test with temp:
Inner = 'abc'
Outer = ''
Test with const:
Inner = 'abc'
Outer = 'abc'
So all works fine...
*/
【问题讨论】:
标签: c++ c++11 visual-studio-2013 type-erasure rvalue