1
#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.

gaurav bharadwaj
  • 1,669
  • 1
  • 12
  • 29
  • 2
    `rvalue` *reference* as a *data member* isn't going to end well.... BTW, you [can't really move integral types](https://stackoverflow.com/questions/14679605/do-built-in-types-have-move-semantics).. – WhiZTiM Oct 25 '17 at 13:38

1 Answers1

1

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405