c++ - 引用 const char*,错误 C2664 :

标签 c++ boost

我正在考虑使用 boost::serialization 并尝试使用在 http://www.ocoudert.com 上给出的字符串助手有接口(interface)

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 和帮助程序行,我会得到编译错误 C2664:无法将参数 1 从“const char *”转换为“char *&”

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

最佳答案

SerializeCStringHelper 助手(lib.getName().c_str());

此行尝试将临时变量传递给 SerializeCStringHelper 的构造函数,问题是您无法将临时变量绑定(bind)到非常量引用。这就是 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 引用。

关于c++ - 引用 const char*,错误 C2664 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17773838/

相关文章:

c++ - 按值接受临时值和按引用接受非临时值的模板函数?

c++ - 自定义输出

c++ - g++ 中的链接问题

c++ - 以纳秒为单位获取本地时间

c++ - 使用带有固定长度数组 typedef 的 new

c++ - 在已经定义运算符C++时不匹配

linux - Ubuntu 12.04 升级 boost 1.46 到 1.60

c++ - 如何打印 Voronoi 图的面?

c++ - 如何使用 Boost.program_options 检测拼写错误?

c++ - 传递参数以在 C++ 中 boost odeint