我正在考虑使用boost::serialization,并尝试使用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 *&’
我的问题是,为什么这一行与两行不同?
发布于 2013-07-21 23:23:27
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接受非常数引用。
https://stackoverflow.com/questions/17773838
复制相似问题