mercredi 4 novembre 2015

VS2013 warning C4172 on return Rvalue

Rvalues are new, so i have some doubts about it...

VS2013 gives

warning C4172: returning address of local variable or temporary

for this line

return (std::wstring&&)         (*(std::wstring*)v);

Is this code (below) unportable and/or have undefined behavior anywhere? If there is - where and why? Am i doing something wrong? Or this is just a false-positive warning of the VS2013 compiler, and i should just put pragma to ignore it in this paticular case?

temp_value_t is intended to use as a container for a cascade of calls:

[typed value] -> calls virtual_func1(temp_value_t) -> calls virtual_func2(temp_value_t) -> ... -> calls virtual_funcLAST(temp_value_t)

and funcLAST implementation knows if temp_value_t is really rvalue or lvalue, so funcLAST know which function should be used.

#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... 
*/

Aucun commentaire:

Enregistrer un commentaire