Re: Glib::ustring strange error msg ??



On Thursday 08 May 2008, Hubert Figuiere wrote:
> On Wed, 2008-05-07 at 22:09 -0400, Jamiil wrote:
> > const Glib::ustring& jve::Person::getTitle(){
> >    switch(title){
> >       case Mr:   {return "Mr";  }
> >       case Mrs:  {return "Mrs"; }
> >       case Miss: {return "Miss";}
> >       case Ms:   { return "Ms"; }
> >       case Dr:   { return "Dr"; }
> >       default:   {return "None";}
> >    }
> > }
> >
> > Glib::ustring msg = person->getTitle(); <<=== this causes an
> > segmentation fault
>
> You are returning a reference to a temporary. Your compiler should have
> told you already with a warning.

Although this is not really a glib/gtkmm issue (it's basic C++) I think it 
deserves a bit more explanation than Hubert's correct but terse response.

Your method is declared as returning a reference, because of that ampersand in 
the first line. This tells the compiler not to return the whole Glib::ustring 
object but only a reference to it. The code then attempts to return one of 
several literal strings. But literal strings are not Glib::ustring, they are 
char[]. Since the method returns a Glib::ustring& the compiler has to insert 
code to first convert the char[] into a Glib::ustring so that it has 
something to take the reference of. And it does so by creating a temporary 
object on the stack. As soon as it has done so it takes a reference and 
returns, and in the process destroys or overwrites the object you've just 
returned a reference to.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]