Home A not quite necessary C++23 feature: copying with auto{}
Post
Cancel

A not quite necessary C++23 feature: copying with auto{}

What it takes to copy an object, especially in templated code? Taking into account that declaring the auto variable is always a copy, one can do this:

1
2
3
4
void func(const auto& something) {
    auto copy = something;
    use(copy);
}

What if we don’t want to declare a new variable but rather copy the object in-place? Then one can do this (decay is needed because the actual type might be a reference type or might have cv-qualifiers):

1
2
3
void func(const auto& something) {
    use(std::decay_t<decltype(something)>{copy});
}

And what if we think that C++ is not hard enough? Then one can do this since C++23:

1
2
3
void func(const auto& something) {
    use(auto{copy});
}

I learned this from a “C++ Weekly” video:

There is a not so convincing feature motivation example in the video.

The comments are more interesting than the video, everyone caught facepalm and asked “what the problem with the old way of copying”, “why don’t introduce std::copy” and so on. It’s hard to not agree with them.

This post is licensed under CC BY 4.0 by the author.

How to prepare a programming contest

📚 Book review: "API Design for C++" (2011)