Alexander Demerdzhiev Alexander Demerdzhiev - 1 month ago 17
C++ Question

C++ default move assignment operator cannot be invoked on class even if class has no constructors defined

While I was making myself familliar with C++14 specification, I have read that, if a class has no explicitly declared Copy Constructor, Copy Assignment Operator, Move Constructor nor Move Assignment Operator, default implementations should be generated by the compiler.

Consider this empty class for thread safe files:

class ThreadSafeFile
{
std::mutex m_mutex;
std::string m_FileName;
std::ofstream m_File;
};


When I try to move assign it like this:

ThreadSafeFile file;

ThreadSafeFile file2 = std::move(file);


I am getting this compilation error:


function "ThreadSafeFile::ThreadSafeFile(const ThreadSafeFile &)" (declared implicitly) cannot be referenced -- it is a deleted function


Why is that so?

Answer

If you look carefully, std::mutex cannot be copied nor moved. Since you have a member that cannot be moved or copied, your move constructor and copy constructor are implicitly deleted. If you want to allow moving your class, you can always use std::unique_ptr.

struct ThreadSafeFile {
    std::unique_ptr<std::mutex> m_mutex;
    string m_FileName;
    std::ofstream m_File;
};