Dangling Reference

From: kaede (kaedeRukawa_jp_at_hotmail.com)
Date: 10/27/03


Date: 27 Oct 2003 09:32:33 -0800

Hi all,

I have a quick question regarding binding temporary to const
reference. I wrote a little toy program to test it, but I don't seems
to understand the behaviour. Consider the following code snipplet:

// Data class, also overload operator<<
class Data { ... };

// Holds the data
class DataHolder
{
   public:
      DataHolder(Data data_): m_data(data_) {} // 1
      void dump() const { cout << m_data << "\n"; }

   private:
      const Data& m_data;
};

Scenerio A)

int main()
{
   DataHolder holder( Data(....) );

   // this line will dump out some garbage. My understanding is that
   // The member variable m_data binds to a temporary copied of Data
   // and when the DataHolder constructor completes, the temporary is
   // destroyed that, the m_data reference is no longer valid
   holder.dump();

   return 1;
}

Scenerio B)
int main()
{
   Data data( .. );
   DataHolder holder( data );
   
   // this line successfully dump the contents of data. I am not sure
why?
   // shouldn't it behaves the same Scenerio A?
   holder.dump();
   return 1;
}

Scenerio C)
Change the DataHolder constructor to the following

DataHolder(Data& data_): m_data(data_) {} or
DataHolder(const Data& data_): m_data(data_) {}

int main()
{
   Data data( .. );
   DataHolder holder( data );
   
   // this line successfully dump the contents of data. I am not sure
why?
   holder.dump();
   return 1;
}

Scenerio D)
Now, rather than using Data as a class, we change data to the
following:

enum Data
{
   LONG,
   FLOAT,
   INT
};

When re-running scenerio A - C, the contents of data seems to be
dumping out
correctly. I am not sure why?

Can anyone enlighten me? Your help is appreciated. Thanks!!!!

Kaede