I’m trying to solve a "stupid" problem I got with Visual Studio Enterprise 2022.
I created a new MFC application from scratch, then I added this single line of code:
CFile testFile = CFile(_T("TEST STRING"), CFile::modeCreate);
When I try to build the solution, I get this error from the compiler:
error C2280: 'CFile::CFile(const CFile &)': attempting to reference a deleted function
I read lot of answers and also the official MS Guide about this error but I still cannot figure how to solve.
Any hint?
Thank you!
>Solution :
CFile objects can’t be copied, but that is exactly what you are trying to do – you are creating a temporary CFile object and then copy-constructing your testFile from it. 1
Use this instead to avoid the copy and just construct testFile directly:
CFile testFile(_T("TEST STRING"), CFile::Attribute::normal);
1: I would be very worried by the fact that the compiler is even complaining about this copy, instead of just optimizing the temporary away, as all modern C++ compilers are supposed to do.
This statement:
CFile testFile = CFile(_T("TEST STRING"), CFile::Attribute::normal);
Is effectively just syntax sugar for this (hence the delete‘d copy constructor being called):
CFile testFile(CFile(_T("TEST STRING"), CFile::Attribute::normal));
Which modern compilers since C++17 onward are supposed to optimize to this:
CFile testFile(_T("TEST STRING"), CFile::Attribute::normal);
However, at least according to MSDN, Visual Studio defaults to C++14 by default. So make sure you are compiling for a later C++ version instead.