Keeping links to links: should this work?

I am testing my understanding of lvalue and rvalue references, intentionally trying to break things down. So say that there is this structure:

struct FooBar
{
    FooBar(int&& number) : rNumber(number)
    {

    }

    int& rNumber;
};

and I create an instance FooBar obj(5). Each attempt to read the reference variable returns the correct result (5). The same thing happens if I use const int&instead int&&.

I noticed that replacing intwith std::stringand reading the link returns an empty string, so I suspect that it gives undefined behavior. This is true? And if so, why does it work with integers?

Update: I create an instance and read it as follows:

FooBar obj(5);
//FooBar obj("Hello"); // For strings...

std::cout << obj.rNumber << std::endl;

Update 2: It also works if you pass a custom type, for example:

struct GooBar
{
public:
    GooBar(int number) : itsNumber(number) 
    {
        std::cout << "In constructor..." << std::endl;
    }

    GooBar(const GooBar& rhs) = delete;
    GooBar(GooBar&& rhs) = delete;

    ~GooBar() 
    {
        std::cout << "In destructor..." << std::endl;
    }

    int itsNumber;
};


struct FooBar
{
    FooBar(GooBar&& number) : rNumber(number)
    {

    }

    GooBar& rNumber;
};

:

FooBar obj(GooBar(5));

std::cout << obj.rNumber.itsNumber << std::endl;

, , :

In constructor...
In destructor...
5
+4
1

.

std::string .

Undefined .


, : ( , , ).

+2

All Articles