By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,784 Members | 1,248 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,784 IT Pros & Developers. It's quick & easy.

Is temporary variable always *const*?

P: n/a
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
Aug 10 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
* 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.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Aug 10 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.