I have a functor whose declaration looks like this:
class logger {
public:
log_t operator() (unsigned _LogLevel) {
return log_t{_LogLevel};
}
};
As in the code, I want this functor to construct and return a log_t object. But the compiler complains that copy constructor of the log_t object has been deleted.
I admit, class type log_t has no copy constructor, only a move constructor and an explicit ordinary constructor with one parameter. Due to log_t is derived from the standard library template class basic_ostream, and the copy constructor of this class has been explicitly deleted, so I can only provides a move constructor to log_t objects.
In addition, this object cannot use static to return a reference due to its lifecycle requirements.
I have added -std=c++11
in the compilation options. In my opinion, regardless of whether the RVO option is turned on or not, according to the C++11 standard, the function return value should give priority to calling the move constructor rather than the copy constructor. In this imitation function, the copy constructor should not be needed, but it actually reports an error.
#include <iosfwd>
#include <ostream> // for template class 'basic_ostream'
class mlog_t
: public std::basic_ostream
<char, std::char_traits<char> > {
public:
explicit mlog_t (unsigned) noexcept{}
mlog_t (mlog_t&&) noexcept{}
mlog_t (mlog_t const&) = delete;
~mlog_t () noexcept{}
mlog_t& operator= (mlog_t const&) = delete;
private:
/**
* This is the handle to the buffer.
*/
mutable void* instance_ptr;
};
class __mcl_mlog_t_ {
public:
mlog_t operator() (unsigned _LogLevel) noexcept{
return mlog_t{_LogLevel};
}
};
__mcl_mlog_t_ mlog;
int main (){
return 0;
}
I got a compilation error:
25 32 C:\Users\test.cpp [Error] use of deleted function 'mlog_t::mlog_t(const mlog_t&)'
I've tried this following answer but I failed: "To make use of this feature of C++11, the constructor (taking int in this case) has to be non-explicit though." ( Can we return objects having a deleted/private copy/move constructor by value from a function? )
What is the reason for this error? How can I solve this problem?
The copy elision is not guaranteed until C++17. Before that time, most compilers would elide the copy, but it was not untill C++17 that this is part of the standard.
Try changing your flag to be -std=c++17
.
Pay specific attention to the paragraph about potentially overlapping subobjects, since you write that you inherit from basic_ostream
.