class Owned
{
public:
Owned() {};
};
class Inited
{
public:
Inited();
Inited(Owned *owned);
Inited &operator=(Owned* itemToAssign);
// Problematic Delcaration
Inited(Inited &itemToCopy);
};
Owned *makeOwned()
{
return new Owned;
}
int main (int argc, char * const argv[]) {
/* ** Compile error here ** */
Inited myInited = makeOwned();
}
The compile error is:
main.cpp:25: error: no matching function for call to 'Inited::Inited(Inited)'
main.cpp:15: note: candidates are: Inited::Inited(Inited&)
main.cpp:11: note: Inited::Inited(Owned*)
main.cpp:25: error: initializing temporary from result of 'Inited::Inited(Owned*)'
So it would appear that GCC is trying to create a temporary and then initialize the "myInited" from that temporary. I gather that would be roughly equivalent to:
const Inited t1(makeOwned()); Inited myInited(t1);
Because the temporary is const, it can't use the copy constructor with the non-const parameter. But, apparently, the presence of this constructor is what causes it to create the temporary in the first place. If I remove this copy constructor then everything compiles without trouble.
I can also fix the problem by declaring:
Inited(const Inited &itemToCopy); /* note the addition of a const */
While adding that that makes sense for this toy example, it doesn't work in the original code where "Inited" is a "smart pointer" object. The "itemToCopy" is expected to relinquish control of the pointer it contains to the newly initialized object and is, therefore, not const in this context.
I could also change the line of code where the error is reported to:
Inited myInited(makeOwned());
Again in the toy code this is not really a problem, but the original code base uses the version with the equals sign "all over the place". That code passes through several other C++ compilers without issue, but it won't compile through XCode.
Right now, it looks like a potential solution would be to add the const copy constructor, and make the embedded pointer of the smart pointer class "mutable". But that seems a bit kludgey.
Can anyone suggest a more elegant solution?
Scott