I'm wondering whether this bit of code is exhibiting the correct C++ behaviour?
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 built in VS2008 the output is:
fooA name: alan
fooA name: foofoo
But when the same code is built in VS2010 it becomes:
fooA name: alan
in copy constructor: alan
fooA name: alan
A copy constructor is being invoked on 'alan' and, despite being passed by reference (or not as the case may be), fooA is unchanged by the called to ChangeName
.
Has the C++ standard changed, has Microsoft fixed incorrect behaviour or have they introduced a bug?
Incidentally, why is the copy constructor being called?