Reputation: 9060
I have a method that has this signature
void SetFoo(QString& foo);
and I'm trying to pass an empty string inline, but none of the following compile
SetFoo("");
SetFoo(QString(""));
(error: no matching function for call to ‘MyClass::SetFoo(QString)’)
but if I create a variable like this, it works.
QString emptyFoo = "";
SetFoo(emptyFoo);
Is there not a way to call the method without creating a variable explicitly?
NOTE: Everything seem to work in windows environment with using vc++ compiler but I encounter the above mentioned compilation error in linux environment using g++.
Upvotes: 2
Views: 1669
Reputation: 31952
You can create a global object as a const QString nullStr()
and use it everywhere- Somewhat similar to Null Object Pattern.
Alternatively as billz mentions, a const
reference to a temporary can exist, so making it const Qstring&
will enable the first 2 versions
Regardless, you should change the reference to const Qstring&
if you dont intend to modify it.
Upvotes: 5
Reputation: 45410
To bind a reference to a temporary object, you need const
qualifier, if QString constructor takes char*
input, try:
void SetFoo(const QString& foo);
It makes sense to pass a reference to outlived variable to SetFoo only:
void SetFoo(QString& foo);
QString s;
SetFoo(s);
. NOTE: Everything seem to work in windows environment with using vc++ compiler but I encounter the above mentioned compilation error in linux environment using g++.
VisualStudio is famous(good or bad way) for its C++ extentions, your code compiles on VS doesn't mean it's the C++ standards. The better way is to turn on compile warning(level 4) when you write code, it should give you a warning for binding a reference to temporary object.
Also lookup C++ standard, lookup compiler manuals to make sure your code is portable.
Upvotes: 2