Why does using this deleted function work?

c++

Solution

Lets have a look at `S`:

struct S {
    S() {}                   // default constructor
    S (const S &) = delete;  // copy-constructor
};

What you have here is a type that can be constructed, but cannot be copied.

Now lets take a look at your functions:

void f1 (S s1) {}    // creates a local copy of its parameter
void f2 (S &s2) {}   // takes a reference to the parameter

When you call `f1(s)`, the function tries to create a copy of `s` - but your type `S` forbids copying - that's why this does not work.

When you call `f2(s)`, the function creates a reference to its parameter - so whatever you do inside `f2` with `s2` is done directly to the original object `s`. There is no way a class can prevent anybody to take a reference of the object.

Problem

``` struct S { S() {} S (const S &) = delete; }; void f1 (S s) {} void f2 (S &s) {} int main() { S s; f2(s); } ``` Since `S(S &s)` is deleted, why does using `f2` not throw an error since when it was declared it passes in the arguments `S &s`? When I use `f1(s)` it throws an error. I've looked at the definition of deleted functions and I thought this would throw an error, but it doesn't. Why?

Original source