Is it possible to tell g++ to use the FOO& operator when constructing the FOO object ?
struct FOO {
FOO( FOO & foo ) { // non-const copy constructor
}
operator FOO&() {
return *this;
}
FOO( int i ) {
}
};
int main() {
FOO a(FOO(5));
}
I currently get the following error:
In function int main():
error: no matching function for call to FOO::FOO(FOO)
note: candidates are: FOO::FOO(int)
note: FOO::FOO(FOO&)
— edit —
Note that I try to setup an object that can exchange the ownership of a resource.
Calling FOO foo1(foo) make foo to lose the ownership of the resource, this mean that foo cannot be const.
Also note that I want to avoid smart-pointer mechanism.
Your conversion operator will never be picked up.
§12.3.2 [class.conv.fct] p1The reason is that the conversions mentioned here (except to cv
void) are already done by so-called standard conversions (qualification conversion (addingconstorvolatile) and identity conversion (binding an object to a reference)) and standard conversions are always preferred to user-defined conversions:§13.3.3.2 [over.ics.rank] p2For your specific case, if you want to transfer ownership, do so in C++11 style, with a move constructor.
Transferring ownership via non-const copy constructors is a very bad idea, as such a type can never be stored in standard containers, see the ugly
std::auto_ptr(replaced bystd::unique_ptrin C++11, which has proper move semantics).