Is temporary variable always *const*?

M

Morgan Cheng

Hi,

This isssue consfuse me.

According to <Thinking in C++>, temporay variable is *const*. like

class X{};
X f(){return X();}
void g1(X&){}
void g2(const X&){}
int main()
{
g1(f() );//Not Ok
g2(f() );//OK,const
}

However, it is also said temporay variable can be modified.
class Y{
public:
Y(int ii){i=ii;}
void incr(){i++;}
private:
int i;
};

Y f(){return Y(0);}

main(){
f().incr();//change
}

Anybody can explan this?


Thanks
 
A

Alf P. Steinbach

* Morgan Cheng:
According to <Thinking in C++>, temporay variable is *const*.

Do you have a reference to such statement?

like

class X{};
X f(){return X();}
void g1(X&){}
void g2(const X&){}
int main()
{
g1(f() );//Not Ok
g2(f() );//OK,const
}

f() produces an rvalue (in C that meant a value that could be on the
right-hand side of a assignment, but not on the left-hand side; C++ has lots
of exceptions to that rule, but it's the conceptual underpinning). An
rvalue cannot be bound directly to a reference to non-const. I'm not sure
exactly why; e.g., the often quoted possibility of modifying the number 42
really doesn't hold up on closer inspection.

An rvalue can be const or non-const.

The above rvalue is non-const, but there are no ways of exploiting that for
class X.

However, if you changed class X to

class X{ public: operator X&() { return *this; } };

you'd make the code compile.

Here the rvalue is not bound directly: it's converted to a reference to
non-const X via the defined operator, and that reference is then bound.

However, it is also said temporay variable can be modified.
class Y{
public:
Y(int ii){i=ii;}
void incr(){i++;}
private:
int i;
};

Y f(){return Y(0);}

main(){
f().incr();//change
}

This is allowed as a special case. If you declared the f result type as 'Y
const' it would be forbidden. Some years ago that was recommended practice
(after all, who'd want to intentionally change a function result value?),
but for various reasons -- it wasn't really helpful and in some cases it
could be a hindrance -- it's not recommended today.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top