Skip to content

Commit 2e40240

Browse files
committed
Add copy elision
1 parent 126010a commit 2e40240

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

content/guaranteed-copy-elision.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
execute: true
3+
---
4+
5+
## What It Does
6+
7+
In C++17 and newer, returning a [prvalue](https://en.cppreference.com/w/cpp/language/value_category.html) of the same type as the function return type,
8+
or initializing an object from a prvalue, is guaranteed to construct the object directly in its destination.
9+
No copy or move constructor is called or required to exist.
10+
11+
## Why It Matters
12+
13+
Before C++17, copy elision was an optimization that compilers were permitted but not required to perform.
14+
Code relying on elision could fail to compile if the copy/move constructor was deleted or inaccessible.
15+
C++17 mandates elision in these cases, making prvalue semantics part of the language definition.
16+
17+
## Example
18+
19+
```cpp
20+
#include <print>
21+
22+
struct Widget {
23+
Widget() { std::println("constructed"); }
24+
Widget(const Widget&) = delete;
25+
Widget(Widget&&) = delete;
26+
};
27+
28+
Widget make() {
29+
return Widget();
30+
}
31+
32+
int main() {
33+
auto w = make();
34+
std::println("done");
35+
}
36+
```

0 commit comments

Comments
 (0)