We help IT Professionals succeed at work.
Get Started

Vector::push_back - why does this not crash

mrwad99 asked
Last Modified: 2013-12-14
Hello !

I have an MFC app ( I know this is C++ area, but it involves vectors which are C++ :) ) that has a dialog.  Now the user adds input to the dialogue which is stored in a structure.  In my main app, I then say something like

CMyDialog dlg;
if (dlg.DoModal() == IDOK) {
  // Get the structure
  MyStructure s = dlg.GetStructure();

Ok.  Now where I thought a problem would lie is the fact that

CMyDialog::GetStructure() is defined as

MyStructure& GetStructure() { return m_structure; }  ###


MyStructure m_structure

is a member variable.

Surely ### is returning a reference to *a local object* hence I am adding a temporary object to vectorObject that should be destroyed as soon as dlg goes out of scope !  But this is not the case !  All structures added to vectorObject remain throughout the lifetime of the application !

I figured this was since push_back adds a copy of the object passed to it, but the dox do not say this.  They also say that push_back takes a reference in itself....surely this complicates it further !?

Why is this ?

(Appologies in advance if I am having a dumb moment...)
Watch Question
Top Expert 2012
This problem has been solved!
Unlock 2 Answers and 22 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE