Move Semantics

Why Not Always Use Move Semantics

If move semantics are more efficient, why not always use them instead of copy semantics?

Illustration representing computer hardware

While move semantics can be more efficient than copy semantics, they are not always appropriate. Here are a few reasons why:

Reason 1: Move semantics modify the source object, leaving it in a valid but unspecified state. If you still need to use the source object after the move, it may not be in the expected state.

Resource A;
Resource B{std::move(A)};

// Undefined behavior, A is in a moved-from state
A.SomeFunction();

Reason 2: Not all types support move semantics. Built-in types like int and double don't have move constructors or move assignment operators. Attempting to use std::move() on them will just trigger a copy.

Reason 3: Move semantics are not always faster than copy semantics. For small objects or objects with cheap copy operations, the overhead of moving may be greater than copying.

Reason 4: Readability and maintainability are important. Overusing std::move() can make the code harder to understand and maintain, especially if it's not clear that the source object is no longer needed.

In general, use move semantics judiciously when you know the source object is no longer needed and when the type supports efficient moves. But don't feel compelled to use them everywhere just for the sake of optimization.

This Question is from the Lesson:

Move Semantics

Learn how we can improve the performance of our types using move constructors, move assignment operators and std::move()

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Move Semantics

Learn how we can improve the performance of our types using move constructors, move assignment operators and std::move()

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved