c++ - reference to a const char*, error C2664: -


i'm looking @ using boost::serialization , trying use string helper given on http://www.ocoudert.com has interface

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

i try use helper in following code (getname() returns 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; } 

which compiles fine, if replace const char* str , helper lines commented out code, compilation error c2664: cannot convert parameter 1 'const char *' 'char *&'

my question is, why single line, different 2 separate lines?

serializecstringhelper helper(lib.getname().c_str());

this line attempts pass temporary constructor of serializecstringhelper problem cannot bind temporary non-const reference. why serializecstringhelper helper(str); works, because str not temporary object.

example:

#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; } 

this code compile fine, because bar takes const reference, if uncomment call foo, fail compile because foo takes non-const reference.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -