# C++: error: use of deleted function 'X::X(const X&)' — copying a non-copyable type

**Code:** `use of deleted function` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

The code needs a function (usually a copy constructor or assignment) that was deleted explicitly or implicitly, as for `std::unique_ptr`, `std::mutex` or classes holding them.

## Meaning

A type becomes non-copyable when a member is non-copyable, when it has a user-declared move operation, or when `= delete` is written. Passing it by value, returning a local from a lambda, or storing it in a container that copies triggers the error. Move it, pass by reference or pointer, or make the type copyable.

## Common causes

- Copying a `std::unique_ptr`, `std::mutex`, `std::thread` or `std::ifstream`
- Class with a non-copyable member is copied implicitly
- Constructor or assignment explicitly `= delete`
- Passing the object by value to a function or lambda capture by copy

## Quick fix

1. Pass by reference (`const T&`) or by pointer
2. Use `std::move(obj)` to transfer ownership
3. Capture with `[&]` or `[p = std::move(p)]` in lambdas

## Detailed fix by platform

### C++

1. Replace copies by moves: `consume(std::move(ptr));`
2. Change `void f(Widget w)` to `void f(const Widget& w)`
3. If copying is really wanted, use `std::shared_ptr` or add a copy constructor

## Code examples

### unique_ptr cannot be copied

```cpp
#include <memory>

void take(std::unique_ptr<int> p);

int main() {
    auto a = std::make_unique<int>(42);
    // take(a);                 // error: use of deleted function 'unique_ptr(const unique_ptr&)'
    take(std::move(a));         // OK: ownership moves, 'a' is now empty
}
```

## How to diagnose

1. **Type** — Which type's copy is deleted?
2. **Call site** — Where is a copy made implicitly?
3. **Intent** — Should it be moved, shared or referenced?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/use-of-deleted-function)
