Is there a C++ variable type that imitates a temporary?

Viewed 392

This is really a terribly silly question to which the answer is probably a simple "no", but I'm going to ask in case there is because it would be quite nice.

I can do this, behaviour is exactly as desired:

struct A { int x; };

A inc(A a) {
    a.x += 1;
    return a;
}

inc({ 1 });

where the fact that { 1 } is a temporary forces that it won't be reused, because it has been left invalid by inc() (because of the use of the move constructor -- please correct me if I am wrong about this!).

But what if I am bad at remembering what { 1 } was supposed to stand for, so I make a variable for it, but I still want to force the requirement that it can't be used twice (I'm trying to make it just like a temporary, but named):

A a = { 1 };
inc(a);
inc(a);

No variation of reference type for a will lead the compiler to complain about the double use -- but the move constructor has been precluded by a not being a temporary.

Is there a solution?

5 Answers
Related