引用const char *,错误C2664:

时间:2013-07-21 15:19:37

标签: c++ boost

我正在考虑使用boost :: serialization并尝试使用http://www.ocoudert.com上提供的字符串帮助器,其中包含接口

SerializeCStringHelper(char*& s) : s_(s) {}
SerializeCStringHelper(const char*& s) : s_(const_cast<char*&>(s)) {}

我尝试在下面的代码中使用这个帮助器(getName()返回一个std :: string)

bool MyUtilities::saveSerialLibraryToFile(const string& fileName, const MyLibrary& lib)
{
    bool saved = false;
    ofstream out(fileName, ios::app);
    if(out.is_open())
    {
        boost::archive::text_oarchive ar(out);
        const char* str = lib.getName().c_str();
        SerializeCStringHelper helper(str);
//      SerializeCStringHelper helper(lib.getName().c_str());
        ar & helper;
        saved=true;
    }
    return saved;
}

编译很好,但现在如果我用注释掉的代码替换const char * str和helper行,我得到编译错误C2664:无法将参数1从'const char *'转换为'char *&amp;'< / p>

我的问题是,为什么单行不同于两条不同的行?

1 个答案:

答案 0 :(得分:2)

SerializeCStringHelper helper(lib.getName().c_str());

此行尝试将临时文件传递给SerializeCStringHelper的构造函数,问题是您无法将临时文件绑定到非const引用。这就是SerializeCStringHelper helper(str);有效的原因,因为str不是临时对象。

示例:

#include <string>

void foo(const char*& str) {}

void bar(const char* const & str) {}

int main()
{
    std::string s("...");
    //foo(s.c_str());
    bar(s.c_str());

    return 0;
}

这段代码编译得很好,因为bar需要一个const引用,但如果取消对foo的调用,它将无法编译,因为foo采用非const引用。

相关问题