Question about references in C++ and GCC Topic is solved

Do you have a typical platform dependent issue you're battling with ? Ask it here. Make sure you mention your platform, compiler, and wxWidgets version.
Post Reply
maxinuruguay
I live to help wx-kind
I live to help wx-kind
Posts: 198
Joined: Sat Oct 28, 2006 3:36 am

Question about references in C++ and GCC

Post by maxinuruguay »

I'm having a little problem with porting my code over to Xcode (GCC) from Visual Studio. I'm still don't understand C++ fully so bear with me. Consider this code:

Code: Select all

m_object->AppendCustomValue(event.GetString())
event.GetString() returns a wxString object (not a reference or pointer)
AppendCustomValue is defined as AppendCustomValue(wxString&)

Xcode pops up an error saying there is no matching function for the call AppendCustomValue(wxString) and that the likely candidate is AppendCustomValue(wxString&)

Apparently, GCC differs from the Visual Studio compiler in that the MSW compiler will auto convert a returned object into a reference and GCC will not. Is this correct?

My workaround code is

Code: Select all

wxString st;
st = event.GetString();
wxString& temp = st;
m_object->AppendCustomValue(temp);
Kind of a pain. Is this how it's done? Thanks.
rjmyst3
Knows some wx things
Knows some wx things
Posts: 49
Joined: Tue Oct 10, 2006 7:02 pm
Contact:

Post by rjmyst3 »

If you change

Code: Select all

AppendCustomValue(wxString&)
to

Code: Select all

AppendCustomValue(const wxString&)
then this

Code: Select all

m_object->AppendCustomValue(event.GetString())
will work.

Here's why:
When you pass the result of event.GetString() to AppendCustomValue(), it is only ever a temporary object. The C++ standard does not allow a reference to nowhere. A const reference will keep the temporary object alive until the the const reference goes out of scope.

That is why it works to pass a temporary into a const reference, but it does not work to pass a temporary into a non-const reference.
Post Reply