Temporaries cannot be bound to references unless they are references-to-const
.
No call to copy constructor as expected
-
04-07-2023 - |
문제
I have some code like this:
int a = 5;
Foo *foo = new Foo(MoreFoo(a),
Bar(a));
// Foo CTOR:
Foo(MoreFoo mf, Bar bar): MoreBar(&mf,bar){}
My compiler gives me an error of type:
no matching function for call to ‘Bar::Bar(Bar)’
note: candidates are:
note: Bar::Bar(Bar&)
no known conversion for argument 1 from ‘Bar’ to ‘Bar&’
The error obviously relates to the code Bar(a)
. Obviously Bar
has appropriate CTOR and CCTOR. I understand why the compiler complains about trying to invoke something like Bar::Bar(Bar)
, I'm creating a nameless variable (Bar(a)
) which has to be copied during the call to the Foo
constructor, but then shouldn’t it just invoke Bar
CCTOR? Why am I getting the error?
Edit:
Why would you ever want to invoke Bar::Bar(Bar)
instead of Bar::Bar(Bar&)
?
해결책
다른 팁
It seems that you declatred the copy constructor of class Bar the following way
Bar( Bar & );
But you need to declare it as
Bar( const Bar & );
if you want to use as an argument a temporary object because temporary objects may not be bound to non-const references.