Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 307
Owen Avatar asked Dec 30 '13 08:12

Owen


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

What type of variable is C '?

Variables are containers for storing data values. In C, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123.

Do loops in C?

do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.

What is used to represent individual characters in C?

The char data type in C Using char , you are able to to represent a single character – out of the 256 that your computer recognises. It is most commonly used to represent the characters from the ASCII chart. The single characters are surrounded by single quotation marks.


1 Answers

I don't think there's a data type for that, but you can use a minimal nested block to limit the scope of the variable - I do this quite often in my code:

{
  A a = { 1 };
  inc(a);
}
inc(a);  //error, `a` is not in scope
like image 82
Angew is no longer proud of SO Avatar answered Oct 09 '22 03:10

Angew is no longer proud of SO