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

[intro.object] Example for p10 #6429

Open
Eisenwave opened this issue Jul 31, 2023 · 1 comment
Open

[intro.object] Example for p10 #6429

Eisenwave opened this issue Jul 31, 2023 · 1 comment

Comments

@Eisenwave
Copy link
Contributor

Eisenwave commented Jul 31, 2023

I think p10 could need an example, ideally on which highlights the idiom of using std::launder to force the creation of one particular type of object.

int x;
new (storage) std::byte[sizeof(x)];              // implicitly begin the lifetime of objects in x
*reinterpret_cast<char*>(&x);                    // unspecified whether placement new created
                                                 // an int object inside x, float, char[], or any other objects

std::memmove(&x, &x, sizeof(x));                 // transparently replace ([basic.life]) x with another object
x = 0;                                           // the new object must be of type (no cv) int because 
                                                 // only that may give the program well-defined behavior

std::memmove(&x, &x, sizeof(x));                 // begin the lifetime of one or multiple objects in the storage of x
std::launder(reinterpret_cast<short*>(&x));      // created object at &x must be of type short int
x = 0;                                           // undefined behavior
@frederick-vs-ja
Copy link
Contributor

frederick-vs-ja commented Aug 2, 2023

I'm afraid that the currently proposed example might be an anti-pattern. Note that it's almost always (if not always) a bad practice to ignore the return of std::launder, and std::launder is marked with [[nodiscard]] (since C++20) as a result.

Perhaps it would be better to write something like *std::launder(reinterpret_cast<short*>(&x)) = 0 instead of a single std::launder call.

On ther other hand, as said in [intro.object]/10, the std::memmove call may recreate or merely rewrite the int object. I'm not sure whether it would be helpful to mention such indeterminism in comments.

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

No branches or pull requests

2 participants