1

I run into some issues because I develop with Visual C++ on Windows, and then also compile on Linux using g++. One thing I ran into that I don't understand is that g++ doesn't seem to be able match data types passed to a function if you pass a reference to the constructor to the function. Specifically, given a method signature like this:

static int to_int(string& value);

If it is called like this:

int id_number = EZXMsg::to_int(string(tokens[index]));

(Where tokens type is a vector<char*>& tokens)

g++ gives the error:

main.cpp:130: error: no matching function for call to 'ezx::iserver::EZXMsg::to_int(std::string)' ../iserver-api/ezxmsg.h:50: note: candidates are: static int ezx::iserver::EZXMsg::to_int(std::string&)

Visual C++ doesn't have problem compiling this though. To fix it for g++, the code needs to be like this:

string value(tokens[index]);
int roid = EZXMsg::to_int(value);

What is the reason for g++ needing that additional line?

4

1 回答 1

8

您正在尝试将临时绑定到非常量引用。这在标准 C++ 中是不允许的。

static int to_int(string& value);
//                ^^^^^^^ non-const reference

int id_number = EZXMsg::to_int(string(tokens[index]));
//                             ^^^^^^^^^^^^^^^^^^^^^^ temporary string: no no!

最可能的解决方案是传递const参考:

static int to_int(const string& value);
//                ^^^^^ const reference: yes yes!

如果您确实需要更改函数内部的字符串(to_int函数不太可能需要),则必须将非临时字符串传递给采用非常量引用的函数:

auto s = string(tokens[index]);
int id_number = EZXMsg::to_int(s); // OK, s is not a temporary
于 2013-07-19T15:50:28.817 回答