Can I access an object in C++ other than using an expression?
According to C++03 3.10/1 every expression is either an lvalue or an rvalue. When I use =
to assign a new value to a variable the variable name on the left of the assignment is an lvalue expression. And it looks like whatever I try to do with a variable it'll still use some expression.
Is there any way to manipulate a variable in C++ other than by using an expression?
The only way would be through a statement, yet not via an expression which is part of such a statement. An example would be a definition, std::string x;
. This calls the default ctor on x
. But does this count as a manipulation to you?
There aren't that many other statements, actually. Loop control statements cannot change objects themselves other than via side effects of the loop control expressions. goto
, break
and continue
can't do it at all. throw
is an expression and catch()
can't change anything, so that pair is also irrelevant. I don't think there's any other non-expression-statement.
You can set the value of a variable without using an expression, but you can't really choose what value it gets. The way I read appendix A of the C++11 standard (the language grammar), a declaration is not an expression. If you write int a;
at function scope, a
will be assigned an indeterminate value. If you write it at file scope, a
will be assigned the value 0. But you can't assign it a value or pass constructor arguments because the act of doing so involves an expression.
Not sure if it answers your question strictly but you can manipulate a variable indirectly. Eg:
int a;
int *pA = &a;
*pA = 5;
Here the value of a
is changed but without any expression involving a
. The expression involves only pA
.
Other than that, there might be side effects of unrelated operations that result in variable change, either intentional or not (such as memory corruption that unintentionally changes some variable).
链接地址: http://www.djcxy.com/p/66962.html