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

8 Upvotes

13 comments sorted by

3

u/FrostshockFTW 20h ago

Most classes you create should define no destructor, copy/move constructor, or copy/move assignment (rule of 0). They will inherit the correct behaviour from their members (eg. if your class manages a resource, but it's in a unique_ptr member, you will get the correct set of implicitly defined functions for free).

https://en.cppreference.com/cpp/language/rule_of_three

1

u/hyperchompgames 20h ago

Thank you that's what I was thinking and what I try to do currently, if I need this kind of behavior I use a smart pointer, that seems to have worked for me so far. But it's good to understand it in full in case I run into some issue.

Thanks for the cppreference link that's helpful.

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.

2

u/IyeOnline 20h ago

Specifically I don't really understand the need for all this when you can use a smart pointer like unique_ptr

Guess how smart pointers are implemented? They are class types with move (and potentially copy) constructors that do things.

Similarly std::string is just a class that has a copy constructor (that creates a new copy of the text) and a move constructor (that takes the source objects owned char array).

nd my understanding is if you return a unique_ptr from a function it is already moved by default?

Yes. Nobably a unique_ptr cannot be copied. It has unique ownership over its pointee. When returning a value from a function, C++ will either elide the return object entirely (RVO/NRVO) or at least return by implicit move.

So when do you actually need a class to overload the move constructor?

You need to do that in the same situations where you would implement a custom destructor or copy constructor: Your class owns some resource that needs to be properly handled. In the case of move, there is two scenarions:

  • Your resource is unique can cannot be shared or copied (unique_ptr, handles, ...).
  • You want to allow for more efficient operations; moving a vector, string, ... if you dont need the old object anymore is much more efficient than copying the contents into a new allocation.

As a practical example, consider

std::vector<std::string> lines;
std::string line;
while ( std::getline( some_file, line ) ) {
  lines.push_back( std::move(line) ); 
  // or better: 
  // lines.push_back( std::exchange(line, {} ) );
}

Sure, you could read in the line, then copy that line variable into the vector. But you dont need this copy of the line anymore: Thus its better to just move it and avoid the copy.

1

u/hyperchompgames 20h ago

Thanks, so move is needed when you want to move struct or class members from an object you no longer need? And so you avoid iteration and maybe creating more memory, and instead just move the reference into the new object.

Thanks this helps I think.

3

u/IyeOnline 20h ago

Yes. But its worth noting that moving

  • still creates a new object (or changes a different one in the case of move-assignment)
  • Only really has any benefit if there is a move constructor or move assignment operator that can actually do such resource stealing. Moving an int or a struct Point { int x; int y } is functionally equivalent to copying. Moving a struct Person { std::string name; } on the other hand has a benefit, because std::string has a move constructor that can "steal resources".

5

u/Ok_Beginning_9943 21h ago

A copy constructor should create copies of resources , and that's expensive.

A move constructor is transferring ownership of resources currently owned by another object. This avoids the copy, so it's cheaper (almost no-cost).

So the key question is: do u want a copy, or do u want to continue using the same resources you already paid to create?

Does that make sense?

3

u/FckXFckMusk 20h ago

With a copy you can still use both objects after the copy,

with a Move you can only use the object that was moved to but the source object shouldn't be used...

2

u/Party_Ad_1892 19h ago

Well the source object will be in a valid but unspecified state, you can still use a moved from object as it is well defined to do so but the user should understand what the state of the xvalue will look like.

0

u/FckXFckMusk 19h ago

absolutely..

1

u/Kadabrium 21h ago

C creates shallow copy

Shallow copy creates double free

Double free created deep copy

Deep copy creates slowness

Slowness brings you back to shallow copy... but this time marking the original as empty so you dont double free anymore