Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const reference binding to an rvalue [duplicate]

Tags:

c++

c++11

Working on this question, I found an inconsistent behavior.

Why reference binding behave different in a constructor from a common function?

struct A {
};

struct B : public A {
  B(){}
private:
  B(const B&);
};

void f( const B& b ) {}

int main() {
  A a( B() ); // works
  A const & a2 = B(); // C++0x: works, C++03: fails
  f( B() );  // C++0x: works, C++03: fails
}

I have tested it for C++03 with g++-4.1 and Comeau 4.2.45.2 in strict C++03 mode and with C++0x extensions disabled. I got same results.

For C++0x was tested with g++-4.4 and Comeau 4.3.9 in relaxed mode and with C++0x extensions enabled. I got same results.

like image 367
fnieto - Fernando Nieto Avatar asked Aug 21 '09 08:08

fnieto - Fernando Nieto


People also ask

What is the best use case for rvalue reference to const?

The following use case could have been IMHO a good use case for rvalue reference to const, though the language decided not to take this approach (see original SO post ). It would usually be advisable to use make_unique and make_shared, but both unique_ptr and shared_ptr can be constructed from a raw pointer.

What is the use of const rvalue in as_const?

Besides std::ref, the standard library also uses const rvalue reference in std::as_const for the same purpose. It is also used as return value in std::optional when getting the wrapped value: constexpr const T&& operator* () const&&; constexpr const T&& value () const &&; template <class T, class...

Why can't I call a function on an object with rvalue-ref?

The T in g is T const, so f 's x is an T const&&. It is likely this results in a comile error in f (when it tries to move or use the object), but f could take an rvalue-ref so that it cannot be called on lvalues, without modifying the rvalue (as in the too simple example above).

Why can't we use =delete() for const lvalues?

The semantics of getting a const rvalue reference (and not for =delete) is for saying: we do not support the operation for lvalues! even though, we still copy, because we can't move the passed resource, or because there is no actual meaning for "moving" it.


1 Answers

A a(B());

is the declaration of a function named a returning an A and taking a pointer to a function without argument returning a B. See here. Add parenthesis and you'll get the error you expect:

A a((B()));
like image 87
AProgrammer Avatar answered Oct 23 '22 23:10

AProgrammer