Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify sol::optional<T&>::emplace #1648

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

cuavas
Copy link
Contributor

@cuavas cuavas commented Nov 17, 2024

See comment on #1606: #1606 (comment)

The implementation for emplace in the optional<T> specialisation is needlessly complex, and the static_assert is testing the wrong thing.

Consider:

	template <class T>
	class optional<T&> {
...
		template <class... Args>
		T& emplace(Args&&... args) noexcept {
			static_assert(std::is_constructible<T, Args&&...>::value, "T must be constructible with Args");

			*this = nullopt;
			new (static_cast<void*>(this)) optional(std::in_place, std::forward<Args>(args)...);
			return **this;
		}
...
	};

Now look at the static_assert – it’s testing that T can be constructed using the argument types passed to emplace. However, the optional<T&> doesn’t hold T, it logically holds T& (although it’s implemented using T* to allow assignment). The only thing that T& can be constructed with is T&. It makes no sense to use variadic arguments.

When called with T&, the static_assert only succeeds by chance when T is copy constructible. It will fail if it isn’t, and it will succeed for other things that T can be constructed with when it shouldn’t.

For example, the static_assert will succeed here, but it won’t work:

sol::optional<std::string&> o; // optional<T&> specialisation where T = std::string
o.emplace(size_t(4), 'X'); // the static_assert passes because T (i.e. std::string) can be constructed with (size_t, char), however it won't work because it needs a reference to a std::string

Conversely, this won’t work when it should

sol::optional<std::unique_ptr<int>&> o; // optional<T&> specialisation where T = std::unique_ptr<int>
std::uniqe_ptr<int> p;
o.emplace(p); // static_assert fails because T (i.e. std::unique_ptr<int>) can't be constructed from std::uniqe_ptr<int>& as it isn't copyable

Since you know T* is trivially destructible and copyable, you could implement emplace as:

		T& emplace(T& arg) noexcept {
			m_value = &arg;
			return **this;
		}

cuavas added a commit to mamedev/mame that referenced this pull request Nov 17, 2024
sol::optional<T&>::emplace was broken, and depended on the compiler not
checking that members exist if the template wasn't instantiated.  See
ThePhD/sol2#1606 and ThePhD/sol2#1648.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant