std::terminate and the noexcept specifier

Implementing a noexcept move assignment operator

How can I implement a noexcept move assignment operator for a custom type?

Abstract art representing computer programming

To implement a noexcept move assignment operator for a custom type, you need to define the operator= member function that takes an rvalue reference to the type and is marked as noexcept. Here's an example:

#include <iostream>
#include <utility>

class MyType {
 private:
  int* data;

 public:
  MyType(int value) : data(new int(value)) {}

  ~MyType() { delete data; }

  MyType& operator=(MyType&& other) noexcept {  
    if (this != &other) {
      delete data;
      data = other.data;
      other.data = nullptr;
    }
    return *this;
  }
};

int main() {
  MyType obj1(10);
  MyType obj2(20);

  obj2 = std::move(obj1);
}

In this example, the move assignment operator:

  1. Checks for self-assignment to avoid deleting the object's own data.
  2. Deletes the current object's data.
  3. Moves the data pointer from the other object to the current object.
  4. Sets the other object's data pointer to nullptr to avoid double deletion.
  5. Returns a reference to the current object.

By marking the move assignment operator as noexcept, you indicate that it guarantees not to throw any exceptions, allowing it to be used in move operations without the risk of leaving objects in an indeterminate state.

This Question is from the Lesson:

std::terminate and the noexcept specifier

This lesson explores the std::terminate function and noexcept specifier, with particular focus on their interactions with move semantics.

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

This Question is from the Lesson:

std::terminate and the noexcept specifier

This lesson explores the std::terminate function and noexcept specifier, with particular focus on their interactions with move semantics.

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