自定义string类里面拷贝构造函数代码:
string(const char* tmp) : str(new char[strlen(tmp) + 1])
{
std::cout << "call2" << std::endl;
strcpy(str, tmp);
}
string(string& tmp) : str(new char[strlen(tmp.str) + 1])
{
std::cout << "call3" << std::endl;
strcpy(str, tmp.str);
}
在main函数里面调用
string str = "hello";
报错提示:
error: invalid initialization of non-const reference of type 'string&' from an rvalue of type 'string'
note: initializing argument 1 of 'string::string(string&)'
string(string& tmp) : str(new char[strlen(tmp.str) + 1])
^
string str = "hello";
after user-defined conversion: string::string(const char*)
string(const char* tmp) : str(new char[strlen(tmp) + 1])
^
我在那个string(string& tmp)的参数前面加上一个const限定,就可以成功编译运行,请问这是为什么?
Because if you define it this way, the
string
type of rvalue cannot successfully match the constructor.const string&
can reference both rvalue and lvalue, whilestring&
can only reference lvalue.Also, as mentioned above, in order to avoid type conflicts with the
namespace
instd
string
, it is best to put it in your ownnamespace
or change the name. .You are using something confusing here. The custom class is called string, and the string in the standard STL is also a string. There is a conflict. When compiling the matching constructor, it thinks that the type string&tmp is the string in the matching STL. Rather than your own custom one.
The problem is here
If you replace it with
string str("hello");
there should be no problem.Because
=
is used here, there is no suitable constructor matched here.string str = "hello";
can be seen asstring str(string("hello"))
.string("hello")
can correctly match thestring(const char*)
constructor, which returns a temporary string object, which is an rvalue. But this rvalue does not know how to convert tostring&
orconst char*
type to constructstr
.Error reporting
invalid initialization of non-const reference of type 'string&' from an rvalue of type 'string'
is for this reason.Then let’s talk about this
string str(string("hello"))
. Don’t think that this will be constructed twice. In fact, it won’t. Becausestring("hello")
has already constructed thestring
object here, it is juststr
and will not be constructed multiple times.The occurrence of this problem depends on what compiler you are using. If you try using VS2013, there will be no such problem.