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?
2
Answers
CFile
objects can’t be copied, but that is exactly what you are trying to do – you are creating a temporaryCFile
object and then copy-constructing yourtestFile
from it. 1Use this instead to avoid the copy and just construct
testFile
directly: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:
Is effectively just syntax sugar for this (hence the
delete
‘d copy constructor being called):Which modern compilers since C++17 onward are supposed to optimize to this:
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.
It seems you are compiling your program using a compiler that does not support C++ 17 or higher.
Before the C++ 17 Standard if the copy constructor is deleted then such a record
is incorrect. The compiler will request that the copy constructor will be available.
Starting from C++ 17 even if the copy constructor is deleted nevertheless this record
is correct.
Here is a demonstration program using gcc 12.2
If to compile the program setting the option
-std=c++14
then the compiler issues the errorHowever if to use the option
-std=c++17
then the program compiles successfully.