CodexBloom - Programming Q&A Platform

C++17 std::optional with move-only types scenarios to compile in MSVC 19.30.30706.0

👀 Views: 54 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
c++17 msvc stdoptional move semantics C++

Can someone help me understand I'm working on a project and hit a roadblock. I'm working with an scenario when trying to use `std::optional` with a move-only type in C++17. Specifically, I'm trying to wrap a custom type that has a deleted copy constructor and only a move constructor. The code compiles perfectly with GCC 11.2, but when I try to compile it with MSVC 19.30.30706.0, I receive a bizarre behavior message indicating that `std::optional` requires a copy constructor. Here's a simplified version of my code: ```cpp #include <optional> #include <iostream> class MoveOnly { public: MoveOnly() = default; MoveOnly(const MoveOnly&) = delete; // Delete copy constructor MoveOnly(MoveOnly&&) noexcept = default; // Default move constructor }; int main() { std::optional<MoveOnly> opt; opt.emplace(); // Trying to emplace a MoveOnly instance return 0; } ``` When I compile the above code with MSVC, I get the following behavior: ``` behavior C2248: 'MoveOnly::MoveOnly': want to access private member declared in class 'MoveOnly' ``` I know that `std::optional` should work with move-only types, so I'm wondering if this is a known scenario with the MSVC compiler version I am using. I've tried updating MSVC and even switching to `/std:c++latest`, but the scenario continues. Is there a workaround or a fix that I can apply to make this compile correctly? This is part of a larger application I'm building. What am I doing wrong? The project is a mobile app built with C++. Thanks in advance!