It is an implementation of class String in The C++ Programming Language. This is my code and I just show a part of them to eliminate the unrelated stuff.
#include <iostream>
class String {
public:
explicit String(const char *x);
explicit String(const String &x);
friend String operator+(const String &, const char *) {
char *str;
String ret(str);
return ret;
}
};
The problem was found in function String operator+(const String &x, const char *y);
Error message said:
error: no matching constructor for initialization of 'String'
return ret;
^~~
note: explicit constructor is not a candidate
explicit String(const char *x) : rep(new Srep(strlen(x), x)) {}
^
But the constructor explicit String(const char *x);
had been implemented. I got confused.
And I tried to eliminate the explicit
in explicit String(const char *x);
, but it gave me another error:
error: no matching constructor for initialization of 'String'
return ret;
^~~
note: candidate constructor not viable: no known conversion from 'String' to 'const char *' for 1st argument
String(const char *x) : rep(new Srep(strlen(x), x)) {}// x = "abc"
^
When I reduce some code, I found that if there is no function explicit String(const String &x);
or this function is not explicit
, error won't occur. Are there any relation between explicit String(const String &x) : rep(x.rep);
and my ret
in String operator+(const String &x, const char *y);
? I think it just creates a String and return it by value but maybe it is wrong?
count
here stands for reference count, if it use copy constructor to return, it would be wrong for count, and if I use String(str)
to return directly, it seems to cause memory leak.