Re: Check if an argument is temporary
On Oct 29, 11:53 am, Klaas Vantournhout <no_valid_em...@spam.com>
wrote:
James Kanze wrote:
The real question is why the OP wants to know. There's likely a
solution to his real problem which doesn't require such
knowledge.
Hmm okay this is what I had in mind.
Assume you have a class array
class array {
public:
array(int N) : n(N) {
if (n) a = new double[N];
else a = NULL;
}
~array(void) { delete [] a; }
array operator=(const array &A) {
if (n != A.n) { delete [] a;
a = new double [A.n]; }
for (register int i=N-1; i >= 0; --i)
a[i] = A.a[i];
return *this;
}
private
double *a;
int n;
}
Assume now we have the function
array foo(void);
which creates an enormous array
Then the following operation
array B;
B = foo();
Creates a tremendous amount of overhead.
A temporary array is created in foo(), this array is passed to operator=
and there each element of foo is copied to B.
However, it would be useful if operator= could notice if the object is
temporary.
Because then we could write
if (temporary) {
a = A.a; A.a = NULL;
}
When this happens, foo gets destroyed after operator=, but it is only a
NULL pointer, the real date is still there and not delete with ~array(void);
Make A::operator= take the argument by Value instead of reference,
then swap 'this' and the argument:
struct A {
A(...) { allocate-and-initialize-p }
A(const A& rhs) { allocate-p-and-intialize-from-rhs }
A& operator=(A x) {
swap(*this, x);
return *this;
}
firend void swap(A& lsh, A& rhs) {
std::swap(lsh.p, rhs.p);
}
private:
whatever * p
};
(you do not really need a friend swap, you could directly swap or
pilfer the pointer inside operator=, but swap is generally useful).
If the argument of operator= is an lvalue, it will perform a copy (and
you would need to do it anyway), which will swaped into 'this' without
making .
If it is a temporary, like in this case:
A foo();
...
A x;
x = foo();+
the compiler is free (and any decent complier will actually do so) to
construct the result of foo directly in the argument slot of
A::operator=, skipping any intermediate temporary. Also note that an
operator= implemented in term of swap has the nice side effect of
being trivially exception safe (your is not, consider what would
happen if 'operator new' throws), safe even in face of self assignment
and does eliminate any code duplicated with the copy constructor.
HTH,
Giovanni P. Deretta