samedi 23 juillet 2016

std::forward Visual Studio 13 doesn't behave like it should

I'm trying to learn some basic C++ 11, using Scott Meyers lecture on youtube called "An Effective C++11/14 Sampler"

https://www.youtube.com/watch?v=BezbcQIuCsY

Using his sample code for std::forward (min 19 in the lecture) I wrote the following code to understand the effect of std::forward

#include "stdafx.h"
#include <string>
#include <utility>

class A
{

public:

    void Foo(std::string&& s)
    {
        std::string s2 = std::forward<std::string>(s);
    }
};



int _tmain(int argc, _TCHAR* argv[])
{
    A a;

    std::string s3 = "Hello World";
    a.Foo(s3);
    a.Foo("Hello World");

    return 0;
}

Surprisingly it doesn't compile, a.Foo(s3) cant implicitly cast from lvalue to rvalue. So I changed a.Foo(s3); to a.Foo(std::move(s3)); Now it compiles. However on both calls to Foo std::forward(s); resolved to an rvalue and a Move operation occurred (s was reset to "" as its buffer was pilfered).

So I really don't understand what good is std::forward and when it does apply. What am I missing here?

Aucun commentaire:

Enregistrer un commentaire