gaurav bharadwaj
gaurav bharadwaj

Reputation: 1771

Rvalue and lvalue references as member variable in a class - Valid?

#include <iostream>
#include <string>
#include <vector>

class X
{
  public:
  int& a;
  int&& b;

  X(int& c, int && d):a(c), b(std::move(d))
  {

  }
};

X* x = nullptr;
void fun()
{

    std::cout<<"Fun\n";
    int l = 8;
    int r = 9;
    std::cout << &(l) << std::endl;
    std::cout << &(r) << std::endl;
    x = new X(l, std::move(r));    
}

int main()
{
  fun();

  std::cout << x->a << std::endl;
  std::cout << &(x->a) << std::endl;

  std::cout << x->b << std::endl;
  std::cout << &(x->b) << std::endl;

}

=> Will values of member variable references (lvalue and rvalue) be garbage?
I am seeing different behavior across different compilers. So wanted to know what c++ standard says about this.

Upvotes: 1

Views: 1119

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

You're binding reference members to local variables, which will be destroyed when get out of the function fun(). After that, both references become dangled, any dereference on them leads to UB.

This is true for both lvalue and rvalue reference members.

Upvotes: 1

Related Questions