How to create an optional for a type with no copy ctor?

Hi,

I want to create an std::optional for a type that has the copy ctor deleted, like for this type User:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct User
{
	User(const std::string& name, const int age)
		: name(name),
		  age(age)
	{
	}

	std::string name;
	int age;
	
	User(const User& usr) = delete;
	User(User&& usr)
	{
		name = std::move(usr.name);
		age = usr.age;
	}
	User& operator=(const User& usr) = delete;
	
};


I tried the following:


 
std::optional u{ User{ "juan", 60 } };



Which gives me these errors:


1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\xmemory(701,82): error C2280: 'User::User(const User &)': attempting to reference a deleted function
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\xmemory(701,82): error C2280:         ::new (const_cast<void*>(static_cast<const volatile void*>(_Ptr))) _Objty(_STD forward<_Types>(_Args)...);
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\xmemory(701,82): error C2280:                                                                                  ^


I also tried:

 
std::optional<User> uu{ std::in_place, "juan", 60 };


with same error.

Any ideas?

Juan
Last edited on
This builds and runs using g++ 8.4.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <string>
#include <optional>
#include <iostream>

using namespace std;

struct User
{
	User(const std::string& name, const int age)
		: name(name),
		  age(age)
	{
	}

	std::string name;
	int age;
	
	User(const User& usr) = delete;
	User(User&& usr)
	{
		name = std::move(usr.name);
		age = usr.age;
	}
	User& operator=(const User& usr) = delete;
	
};

int main()
{
  optional<User> opt{User("Juan", 60) };
  cout << opt->name;
}

I am using VS 2019 version 16.8.2.


The problem must lie in the Visual C++ definition of std::optional. My question remains the following:

Why is the copy ctor being called in these lines of code: (I can't see a reason for this....)

1
2
std::optional u{ User{ "juan", 60 } };
std::optional<User> uu{ std::in_place, "juan", 60 };



And more important: how can I create an optional for a class that is not copy constructible?
What can I do to the code to make creating optionals work for non-copy constructible types?

Any help?

Juan
Last edited on
Topic archived. No new replies allowed.