r/cpp_questions • • 21h ago

SOLVED When to use copy/move constructors?

SOLVED: There's already been a lot of good answers. I understand much better now. The video here and the reply here were especially helpful. Thanks everyone, great community I did not expect to get such good answers so quickly :)

I'm sort of new to C++ dev, but not at all new to programming. I have some experience in C and old style C++ (ie writing C++ as though it's C). But now I'm trying to properly learn more modern C++, I'm using C++ 20 at the moment.

I've spent a lot of time recently learning about lvalues and rvalues, copy and move semantics. This has been rough to grasp vs C where everything is by value and the only thing you really think about is whether you pass with a pointer or not.

At this point I think I understand how it works. I know how to implement copy constructors, move constructors, and how to use smart pointers like unique_ptr and shared_ptr. I also learned how to create custom deleters for wrapping C libraries so I can use smart pointers with them if I choose to.

The issue now is I feel like there are so many options it's hard to think of when you need each thing. Specifically I don't really understand the need for all this when you can use a smart pointer like unique_ptr, and my understanding is if you return a unique_ptr from a function it is already moved by default? Is that correct?

So when do you actually need a class to overload the move constructor? This is what I don't understand. And why not just pass by lvalue &reference instead? I know smart pointers don't have that option, but that's what std::move is for, right?

I guess it's like at this point I get the rvalue is a literal, temporary value, but I don't really understand what the benefit of passing in this manner is as opposed to passing by lvalue reference? And I don't understand WHEN to do it, because all the information I find focuses solely on the how but not the why.

EDIT: fixing code snippet formatting

6 Upvotes

13 comments sorted by

View all comments

2

u/Hkiggity 21h ago

https://youtu.be/F-7Rpt2D-zo?is=h8Y1uKNH8g6d2QM3

I remember watching this a while ago. And i think it’s a good explanation

2

u/hyperchompgames 20h ago

You saved my life (and brain) with this. This video is a very good explanation. Coming from C this is pretty much the same problem you get when you have Structs with malloc'd struct pointers in them.

2

u/Hkiggity 19h ago

Glad it helped. I’d also recommend https://www.learncpp.com/cpp-tutorial/move-constructors-and-move-assignment/ or learn cpp in general when something like this comes up.

Also if you ever are curious about things like that, check out ccpcon talks, For example: https://youtu.be/St0MNEU5b0o?is=rbhPmZMajeZUPlGT

If there’s a topic like move semantics or something else. See if there’s a back to basics talk on it. Those talks are freaking awesome man.