Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Deleted functions

Use case

Prevent copying of resources that cannot be safely duplicated.

Explanation

= delete disables a function entirely. Copying is deleted here because unique_ptr cannot be copied. Attempting to copy gives a compile error. Move is still allowed since it transfers ownership safely. According to the rule of 5, we implement all.

Code

#include <iostream>
#include <memory>

class CodeBuffer {
  std::unique_ptr<uint8_t[]> data;
  size_t size;

public:
  CodeBuffer(size_t s) : data(new uint8_t[s]), size(s) {
    std::cout << "Allocated " << size << " bytes.\n";
  }

  ~CodeBuffer() { std::cout << "Freed " << size << " bytes.\n"; }

  // Move constructor.
  CodeBuffer(CodeBuffer &&other) noexcept
      : data(std::move(other.data)), size(other.size) {
    other.size = 0;
  }
  // Move assignment.
  CodeBuffer &operator=(CodeBuffer &&other) {
    if (this != &other) {
      data = std::move(other.data);
      size = other.size;
      other.size = 0;
    }

    return *this;
  }

  // Copy constructor.
  CodeBuffer(const CodeBuffer &) = delete;
  // Copy assignment.
  CodeBuffer &operator=(const CodeBuffer &) = delete;
};

int main() {
  CodeBuffer a(1024);
  // function "CodeBuffer::CodeBuffer(const CodeBuffer &)" cannot be referenced
  // -- it is a deleted function
  // CodeBuffer b = a;
  CodeBuffer b = std::move(a);
  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/deleted-functions
Allocated 1024 bytes.
Freed 1024 bytes.
Freed 0 bytes.