Reputation: 10480
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?
Upvotes: 4
Views: 204
Reputation: 1941
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.
Upvotes: 9
Reputation: 258568
Because passing by reference doesn't create a copy (which is what f2
uses).
f1
, on the other hand, takes a pass-by-value parameter, which makes a copy.
Upvotes: 10