I'm having some weird behaviour with the following:
using namespace std;
struct Number
{
Number(int init) : a(init) {}
Number() {};
int a;
static Number& getNumber() { return Number(555); }
//Number(const Number& other)
//{
// a = other.a;
//} // I've commented this out you'll see why
};
int main()
{
Number num1; // Is now junk
Number num2; // Is now junk
num2 = Number::getNumber(); // num 2 is still junk
Number num3 = Number::getNumber(); // num3 has been assigned 555.
// If I define my own copy constructor
// (uncomment it), it stays junk.
cout << num3.a;
}
When I make my own copy constructor, whether it takes a const or not, the value coming in in the "other" argument is junk. I don't get this behaviour if the copy constructor is the default one. I tried it on IDEOne using GCC and this code doesn't compile. However on my Visual Studio it runs as I described.
I find it really hard to understand the rules of how long a temporary is still valid. For example, I thought that if getNumber() returns a reference to a local temporary, it's OK if it's assigned directly on the same line. I was wrong.