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!
CodePudding user response:
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.
CodePudding user response:
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
CFile testFile = CFile(_T("TEST STRING"), CFile::Attribute::normal);
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
CFile testFile = CFile(_T("TEST STRING"), CFile::Attribute::normal);
is correct.
Here is a demonstration program using gcc 12.2
int main()
{
struct A
{
A( const char *)
{
}
A( const A & ) = delete;
};
A a = A( "Hello C 17!" );
}
If to compile the program setting the option -std=c 14
then the compiler issues the error
<source>:207:33: error: use of deleted function 'main()::A::A(const main()::A&)'
207 | A a = A( "Hello C 17!" );
However if to use the option -std=c 17
then the program compiles successfully.