[C++0x] l-values and r-values

M

Michael Tsang

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

1. Is the following possible:

int a = 3;
int && b = a;


2. I want to write the signatures of extractors in this way:

#include <iosfwd>
class foo_t;

template<class charT, class Traits>
std::basic_istream<charT, Traits> &operator>>(std::basic_istream<charT,
Traits> &&in /* note the r-value reference */, foo_t &object);

Is this a good idea?

3. For the swap function:

template<class T>
swap(T &a, T &b) {
T c = (T &&)a; // a is now destroyed
a = (T &&)b; // b is now destroyed
b = (T &&)c; // c is now destroyed
}

Is this OK. What is the difference between std::move and a cast to r-value
reference? What C++ casting operator is the most suitable for replacing the
C-style casts?

4. Is it useful to have const class r-values? Do we need to write
constructors from a const r-values (const foo_t &&) of the same type?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkuE5ysACgkQm4klUUKw07D3GwCdGWBovX+hcCDvqo1v+SHdgC6V
LDYAn3wKmAFYHxNjQDVmQQZ2XEKugF52
=anc2
-----END PGP SIGNATURE-----
 
N

Niels Dekker - no reply address

Michael said:
1. Is the following possible:
int a = 3;
int && b = a;

No, you would need to do an explicit cast:
int && b = static_cast<int&&>(a);

Or use std::move:
int && b = std::move(a);
2. I want to write the signatures of extractors in this way:

#include <iosfwd>
class foo_t;

template<class charT, class Traits>
std::basic_istream<charT, Traits> &operator>>(std::basic_istream<charT,
Traits> &&in /* note the r-value reference */, foo_t &object);

Is this a good idea?

Looks fine to me.

3. For the swap function:

template<class T>
swap(T &a, T &b) {
T c = (T &&)a; // a is now destroyed
a = (T &&)b; // b is now destroyed
b = (T &&)c; // c is now destroyed
}

Is this OK.

I think it will work, but I'd rather not use C-style casts. BTW, an object
is not really "destroyed", when it is moved-from. (Its destructor is not
yet called.)
What is the difference between std::move and a cast to r-value
reference? What C++ casting operator is the most suitable for replacing
the
C-style casts?

4. Is it useful to have const class r-values?

There are some use cases for const rvalue-references. But those use cases
are pretty rare!
Do we need to write constructors from a const r-values
(const foo_t &&) of the same type?

Usually not.

HTH,

Niels
 

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

No members online now.

Forum statistics

Threads
474,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top