Correct conditional statement behavior in VS2010?

I am wondering if this bit of code demonstrates the correct C ++ behavior?

class Foo
{
public:
    Foo(std::string name) : m_name(name) {}

    Foo(const Foo& other) { 
        std::cout << "in copy constructor:" << other.GetName() << std::endl;
        m_name = other.GetName();
    }

    std::string GetName() const { return m_name; }
    void SetName(std::string name) { m_name = name; }

private:
    std::string m_name;
};

Foo CreateFoo(std::string name)
{
    Foo result(name);
    return result;
}

void ChangeName(Foo& foo)
{
    foo.SetName("foofoo");
}

int _tmain(int argc, _TCHAR* argv[])
{
    Foo fooA("alan");
    std::cout << "fooA name: " << fooA.GetName() << std::endl;
    bool b = true;
    ChangeName(b ? fooA : CreateFoo("fooB"));
    std::cout << "fooA name: " << fooA.GetName() << std::endl;
    return 0;
}

When building in VS2008 output:

fooA name: alan
fooA name: foofoo

But when the same code is embedded in VS2010, it becomes:

fooA name: alan
in copy constructor: alan
fooA name: alan

The copy constructor is called on 'alan', and despite the fact that it is passed by reference (or cannot be in that case), fooA does not change the called by ChangeName.

Has the C ++ standard changed, has Microsoft fixed the wrong behavior, or indicated an error?

By the way, why is the copy constructor called ?

+3
source share
5 answers

More complete answer:

5.16 / 4 & 5:

"4 lvalues ​​ , lvalue.

5 r... "

, "bool? lvalue: rvalue" .

, , , ++, lvalue . rvalue, , ++. MSV++ , , , . ++ , MS , , "" .

+5

lvalue Foo, rvalue Foo ( , ).

, rvalue, lvalue ( ), . , , , .

lvalue, lvalues ​​ .

: , , .

+3

, ++ 5.16 3, ?

: " E2 rvalue : E1 E2 , : E1 E2, T2 , T1, cv- T2 cv-, cv-, cv -qualification T1. , E1 rvalue T2, ( ). [: .]"

? , , , , - , .

.

0

, ", 4 ". ( ), , , , "ChangeName" . , const-, , . , vaguary Microsoft.

0

:.

-1

Source: https://habr.com/ru/post/1764983/


All Articles