Reputation: 54183
In msvc, I have functions like this and it builds but in gcc it doesnt like it.
void classname::a(std::string &text)
{
stdStringFromClass = text;
}
void classname::b(char *text)
{
a(std::string(text));
}
The issue here is in the &, gcc I think is worried that since I just created that std::string, that passing by reference is risky, so it does not build, but msvc doesnt even warn me.
Why is this incorrect c++ to gcc I keep hearing that msvc is stricter than gcc.
Thanks
The error
AguiWidgetBase.cpp: In member function ‘void AguiWidgetBase::setText(char*)’:
AguiWidgetBase.cpp:91:27: error: no matching function for call to ‘AguiWidgetBase::setText(std::string)’
AguiWidgetBase.cpp:80:6: note: candidates are: void AguiWidgetBase::setText(std::string&)
AguiWidgetBase.cpp:88:6: note: void AguiWidgetBase::setText(char*)
would this be okay?
void classname::a(std::string &text)
{
stdStringFromClass = text;
}
void classname::b(char *text)
{
std::string k = text;
a(k);
}
Upvotes: 3
Views: 1757
Reputation: 6307
I believe someone else said this first, but passing a reference to an anonymous object is illegal. Visual C++ is weird. To fix it, try something like this:
void class::a(const std::string &text)
{
stdStringFromClass = text;
}
void class::b(const char *text)
{
a(std::string(text));
}
BTW, I assume your class name is not actually 'class', and you're just using that as a placeholder, because
class class {
// ...
};
stuff is illegal.
Upvotes: 3
Reputation: 15164
Without the actual error message I can only guess: class is a reserved keyword and you should name your class differently, this is not a valid method definition:
void class::a(std::string &text) { ... }
EDIT: the problem is in passing the anonymous reference, as others have pointed out. You can just ignore this answer now.
Upvotes: 0
Reputation: 36451
I have no idea why Visual studio allows you to compile this, but you can't pass a reference to an anonymous object.
Edit: Its ok for const reference, cause you can pass the temporary object as reference, just being able to modify it doesn't make sense. That's why we have rvalue references in C++0x.
Edit2: To your edit, yes that would fix the problem, or just take a const reference as parameter in the a()
method, you don't seem to modify the parameter.
Upvotes: 3
Reputation: 80031
I think this is an old compiler extension that Visual Studio supported since way back then, but it is kept around in modern Visual C++ for compatibility. Try disabling compiler extensions (/Za
flag) and see what happens.
Alternatively, use the /W4
flag to get maximum warnings, and it should complain:
warning C4239: nonstandard extension used
On GCC I get the const reference error:
error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’
Upvotes: 6