编译器将字符串转换为basic_string <>&

Sht*_*ong 1 c++ g++

我花了很长时间在其他技术上花了很长时间才回到C++,当调用一些以std :: string作为参数的方法时,我会遇到一些奇怪的行为:

电话的一个例子: LocalNodeConfiguration *LocalNodeConfiguration::ReadFromFile(std::string & path) { // ... throw configuration_file_error(string("Configuration file empty"), path); // ... }

当我编译时,我得到了这个(为了便于阅读,我裁剪了文件名):

/usr/bin/g++    -g -I/home/shtong/Dev/OmegaNoc/build -I/usr/share/include/boost-1.41.0   -o CMakeFiles/OmegaNocInternals.dir/configuration/localNodeConfiguration.cxx.o -c /home/shtong/Dev/OmegaNoc/source/configuration/localNodeConfiguration.cxx
    .../localNodeConfiguration.cxx: In static member function ‘static OmegaNoc::LocalNodeConfiguration* OmegaNoc::LocalNodeConfiguration::ReadFromFile(std::string&)’:
    .../localNodeConfiguration.cxx:72: error: no matching function for call to ‘OmegaNoc::configuration_file_error::configuration_file_error(std::string, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’
    .../configurationManager.hxx:25: note: candidates are: OmegaNoc::configuration_file_error::configuration_file_error(std::string&, std::string&)
    .../configurationManager.hxx:22: note:                 OmegaNoc::configuration_file_error::configuration_file_error(const OmegaNoc::configuration_file_error&)
Run Code Online (Sandbox Code Playgroud)

据我了解,编译器正在考虑我的路径参数在某个时刻转变为basic_string,因此找不到我想要使用的构造函数重载.但我真的不明白为什么会发生这种转变.

网上的一些搜索建议我使用g ++,但我已经在使用它了.所以任何其他建议将不胜感激:)

谢谢

ken*_*ytm 12

问题不basic_string在于,因为basic_string<char, restOfMess>相当于string.

问题是该功能仅提供

f(string&, string&) {
//------^
Run Code Online (Sandbox Code Playgroud)

但你打电话给

 f(string("blah"), path);
// ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

这是一个rvalue(临时对象),并且rvalue不能绑定到可变引用.您需要更改原型以接受const引用或仅传递值:

    f(const string&, string&) {
//----^^^^^^
or
    f(string, string&) {
Run Code Online (Sandbox Code Playgroud)

或者提供一个可变引用(如果你真的需要修改该函数中的第一个参数):

string s = "blah blah blah";
f(s, path);
Run Code Online (Sandbox Code Playgroud)