Value Categories

More on C++ Value Categories · Ranting Jacaré (rafaeljin.gitlab.io)

  1. Literals
    1. no name, cannot be referred to again
    2. these are called pure values or prvalues
  2. Temporary objects
    1. represent object and their data can be moved
    2. they are known as xvalues (x for “eXpiring?”)
  3. lvalue
  • Every expression has a type and a value category

Info

lvalues and xvalues are objects
their dynamic type can be different from their static type
they are collective known as generalized lvalues or glvalues

lvalue & rvalue

x = 2;
x = func();

lvaluervalue
x has a name2 has no name
&x is legal&2 is illegal
return value from a func has no name
&func() is illegal

Warning

lvalue and rvalue behave different when passed as function arguments

  1. rvalue can be passed by reference to const to a function

lvalue

rvalue

Pass by move

std::move

  • want to pass an lvalue to a function which takes an rvalue reference —> cast to rvalue
  • std::move() will cast its argument to rvalue
int y{2};
func(std::move(y)); // y is cast to an rvalue, OK
  • this will move y’s data to the function argument x

Warning

This should only be done if y’s data is expendable
After calling func(), y’s data may be empty or unusable
If we want to use y again, we must re-assign its data

Move only types

  • fstream
  • iostream
  • Classes used in multithreading
  • Smart pointer class
    These types follow RAII idiom
    The ownership of the resource can be transferred from one object to another using move semantics

fstream

  • fstream object has a file handle as data member
  • fstream constructor opens the file
  • fstream destructor closes the file
  • an fstream object cannot be copied but can be moved
    • the moved-from object no longer own the file handle
    • It has a null handle
    • the moved-to object becomes the owner of the file handle
    • the file will be closed when the moved-to object is destroyed

Capture by move

See Lambda

Collapsing rules

Forwarding References