【问题标题】:reference to a const char*, error C2664:引用 const char*,错误 C2664:
【发布时间】:2013-07-20 09:03:02
【问题描述】:

我正在考虑使用 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: cannot convert parameter 1 from 'const char *' to 'char *&'

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

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

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

    这一行试图将一个临时值传递给SerializeCStringHelper 的构造函数,问题是你不能将一个临时值绑定到一个非常量引用。这就是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 引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多