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 ?
source
share