[英]reference to a const char*, error C2664:
我正在使用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 *&'
我的問題是,為什么單行與兩行不同?
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引用而無法編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.