r/cpp • u/stanimirov • Jul 04 '18
Be Mindful with Compiler-Generated Move Constructors
https://ibob.github.io/blog/2018/07/03/compiler-generated-move/
92
Upvotes
r/cpp • u/stanimirov • Jul 04 '18
15
u/miki151 gamedev Jul 04 '18
What's the reason for move constructors being able to throw?
12
u/mcmcc #pragma once Jul 04 '18
Yeah but it must use type erasure so (unless I'm forgetting something) the lambda capture itself must be dynamically allocated which means the move could just be a
unique_ptrmove.In reality, they're probably leveraging some kind of small buffer optimization, forcing moves to be nontrivial... so then it's just a QOI issue.
3
u/[deleted] Jul 05 '18
What does this mean? The code below compiles without any error.
4
u/zzzthelastuser Jul 04 '18
Can you add some sort of tldr/conclusion to your blog?
11
u/sphere991 Jul 04 '18 edited Jul 04 '18
That's not quite right.
std::functionnever needs to move the underlying type, and wouldn't erase the move constructor anyway - it's unnecessary, it just erases the copy constructor.std::function's move constructor could be made noexcept, and there is a paper that nearly got adopted in Rapperswil that would do just that: P0771. Indeed, on recent versions of libstdc++ and libc++,static_assert(std::is_nothrow_move_constructible_v<std::function<void(int)>>)does not fire.8
u/OldWolf2 Jul 04 '18
Sounds like you need a
unique_ptr<std::function<void(int)>>to keep the rule of zero. (/s ... maybe)5
u/NotMyRealNameObv Jul 04 '18
If being no-throw movable is important, just add
?
6
u/drjeats Jul 05 '18
C++ is a weird mess.
4
u/remotion4d Jul 04 '18
So current exceptions make c++ harder to use?
Can "Zero-overhead deterministic exceptions: Throwing values" proposal make things easier?
-12
u/Xaxxon Jul 04 '18
please spell check posts before linking them here.