提问者:小点点

引用const char*,错误C2664:


我正在考虑使用boost::序列化,并试图使用http://www.ocoudert.com上给出的字符串助手

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

我尝试在下面的代码中使用这个助手(getName()返回一个std::字符串)

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*

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


共1个答案

匿名用户

SerializeCStringHelper助手(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引用。