Skip to content

[cxx-interop] Allow creating Dictionary from std::map #82817

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

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

Conversation

egorzhdan
Copy link
Contributor

This adds an initializer to Swift.Dictionary that takes an instance of std::map or std::unordered_map.

rdar://155050682

@egorzhdan egorzhdan added the c++ interop Feature: Interoperability with C++ label Jul 5, 2025
@egorzhdan
Copy link
Contributor Author

@swift-ci please test

This adds an initializer to `Swift.Dictionary` that takes an instance of `std::map` or `std::unordered_map`.

rdar://155050682
@egorzhdan egorzhdan force-pushed the egorzhdan/dictionary-init branch from b7b6ee0 to 19c7884 Compare July 5, 2025 20:54
@egorzhdan
Copy link
Contributor Author

@swift-ci please test

self[it.pointee.first] = it.pointee.second
it = it.successor()
}
withExtendedLifetime(dictionary) {}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this do?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This prevents a use-after-free caused by the compiler destroying dictionary before the end of the block. Unlike C++, Swift doesn't generally have lexical lifetimes, so the compiler is allowed to destroy a variable after its last use. The last use of dictionary here is the call to __endUnsafe(), after which the dictionary might be destroyed, and the iterators will point to invalid addresses.

This kind of issues is why begin() and end() are imported as unsafe methods in Swift, and it's the main reason for providing the Cxx overlay.

@egorzhdan
Copy link
Contributor Author

@swift-ci please test

@egorzhdan egorzhdan marked this pull request as ready for review July 7, 2025 12:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
c++ interop Feature: Interoperability with C++
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants