patman
patman

Reputation: 3

ostream::operator<< is not working with operator-> in shared_ptr

#include<fstream>
#include<string>
#include<memory>
class Log
{
private:
    string errorlog;
    shared_ptr<ofstream> fs;
public:
    Log() :errorlog(""), fs(new ofstream("c:\\Log\\log.txt"), [](ofstream& fs) {fs.close(); })
    {

    }
    void transferLog(string errorlog)
    {
        (*fs)<<(errorlog)    //is working
         fs->operator<<(errorlog);    //not working

    }
}

i know that if it works,it works well in other common situation.

this error list

no instance of overloaded function "std::basic_ofstream<_Elem, _Traits>::operator<< [with _Elem=char, _Traits=std::char_traits<char>]" matches the argument list

Upvotes: 0

Views: 51

Answers (1)

user743382
user743382

Reputation:

Well don't do that then.

An overloaded operator<< may be defined in one of two ways. It may be defined as a member function, which can be called as fs->operator<<(errorlog);, or it may be defined as a free-standing function, which can be called as operator<<(*fs, errorlog);.

For standard output streams, some overloads use the first form, others use the second form. If you pick the wrong form, things break. Unless you have a very specific use case where you need to use one or the other, just write *fs << errorlog;: that considers both forms and picks the best overload from both sets.

Upvotes: 3

Related Questions