How C++ reference works

前端 未结 5 1134
别那么骄傲
别那么骄傲 2020-12-17 05:54

After working 15 years in C++ I found that I don\'t understand references completely...

class TestClass
{
public:
    TestClass() : m_nData(0)
    {
    }

    T         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 06:35

    Your code suffers from multiple problems and ultimately won't make sense. However, let's hack through it.

    1) You can only bind a temporary to a const reference, thus extending its lifetime:

    const TestClass & c = TestClass();
    

    2) Now we can't use dump, because you didn't declare it const:

    void Dump() const
    

    3) Saying c = TestClass() is an assignment. However, c is now a reference-to-const, which cannot be assigned to, since assignment is non-constant (for obvious reasons). Let's hack around this:

    const_cast(c) = TestClass(10);
    

    Now we've assigned a new value to the temporary-but-extended object c, and all is as it should be:

    main started
    data = 0  ptr = 0x0xbfa8219c
    destructor
    data = 10  ptr = 0x0xbfa8219c
    main ended
    destructor
    

    The pointers are the same because there's only one object, namely the (temporary) one referenced by c. Assigning to it is a hack that's undefined behaviour in general, but we get away with it for the purpose of this demonstration.

    The intermediate destructor is that of the second temporary TestClass(10).

提交回复
热议问题