JHeni
JHeni

Reputation: 751

c++ How to pass an rvalue Reference to another function

I'm using the embedded templated library with etl::queue

https://www.etlcpp.com/queue.html

the etl::queue is quitvalent to std::queue

In order to avoid copying I'd like to actually move the element into the queue.

Now my setup looks like this

  bool CETLConcurrentQueue<ElementType_T, u32QueueSize>::Add(ElementType_T &&element, const uint32_t u32Timeout)
{
   //lock mutex...
   queue.push(element);
   //do further stuff
}

Now I'm not using queue.push(std::move(element)); because element is allready an rvalue Reference

However, queue.push(element); calls elements copy constructor (which is deleted) How can I call elements move constructor instead?

Upvotes: 1

Views: 1067

Answers (1)

songyuanyao
songyuanyao

Reputation: 172904

You have to use std::move to convert element to rvalue. As a named variable element itself is an lvalue, even its type is an rvalue reference.

queue.push(std::move(element));

Note that types and value categories are two independent things.

(emphasis mine)

Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category.

...

The following expressions are lvalue expressions:

  • the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

Upvotes: 5

Related Questions