I am using msvc compiler with C++ 23
I have a situation like this (class shouldn’t be moveable, only copyable):
#include <cstring>
struct MyClass
{
MyClass() = default;
//copy
MyClass(const MyClass& other) { data = other.data; }
MyClass& operator=(const MyClass& other) { data = other.data; return *this; }
//cannot allow move for this class
MyClass(MyClass&& other) = delete;
MyClass& operator=(MyClass&& other) = delete;
int data = 0;
};
int main()
{
MyClass m = MyClass{}; //tries to use move
//works
MyClass newm{};
m = newm;
}
When I do:
MyClass m = MyClass{}; //tries to use move
It tries to move the newly constructed class. I realize that this is natural since MyClass{}
is an r-value.
Is there anything that I can do to the class to make this possible? Make the compiler understand that I want it to use copy since move is deleted, so that MyClass m = MyClass{};
works?
Error message:
error C2280: 'MyClass::MyClass(MyClass &&)': attempting to reference a deleted function
message : see declaration of 'MyClass::MyClass'
message : 'MyClass::MyClass(MyClass &&)': function was explicitly deleted
5
I am using msvc compiler with C++ 23
Are you SURE you are actually compiling with C++23? Modern MSVC supports C++23, but it defaults to C++14. To actually enable C++23, you need to use the /std
flag in your configuration.
In C++17 and later, MyClass m = MyClass{};
is optimized to be identical to MyClass m{};
but that is not the case in earlier versions.
Your code compiles fine in msvc v19 using /std:c++latest
.
Online Demo