编译器转动字符串&进入basic_string<>&

时间:2010-04-22 19:18:41

标签: 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&)

据我了解,编译器正在考虑我的 path 参数在某些时候变成了basic_string,因此找不到我想要使用的构造函数重载。但我真的不知道为什么会发生这种转变。

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

由于

3 个答案:

答案 0 :(得分:12)

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

问题是该功能仅提供

f(string&, string&) {
//------^

但你打电话给

 f(string("blah"), path);
// ^^^^^^^^^^^^^^

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

    f(const string&, string&) {
//----^^^^^^
or
    f(string, string&) {

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

string s = "blah blah blah";
f(s, path);

答案 1 :(得分:2)

这里的问题是configuration_file_error构造函数的第一个(好的,两个,但第一个是导致问题的那个)参数是非const引用,你可以'将临时对象(就像你试图传入的对象)绑定到非const引用。

如果不需要修改字符串,构造函数可能应该使用const引用。既然你把它作为一个例外,我希望它不需要修改它的参数,因为它们引用的对象可能会在堆栈被解开时被销毁!

答案 2 :(得分:0)

string只是basic_string<>的别名。从标准(§21.2),无疑直接复制到您的头文件,

typedef basic_string<char> string;

其中basic_string<char>

获得两个默认参数
template<class charT, class traits = char_traits<charT>,
class Allocator = allocator<charT> > class basic_string;

这些参数有些神秘,除非你手动覆盖它们,否则不会改变。

basic_string<wchar_t>是您可能遇到的与Unicode不同的类型。)