请考虑以下代码:
#include <string.h>
class cstring {
public:
cstring(const char* str) : begin_(str), end_(str ? str + strlen(str) : 0)
{
}
size_t size() const
{
return (size_t)(end_ - begin_);
}
const char* data() const
{
return begin_;
}
private:
const char* begin_;
const char* end_;
};
class Name {
public:
Name(cstring str)
{
}
};
int main()
{
cstring str = "Hello World"; // OK
Name name = str; // OK
Name name2 = "James"; // error
}
Clang 会输出错误(GCC 也有类似的输出):
Source.cpp:37:10: error: no viable conversion from 'const char [6]' to 'Name'
Name name2 = "James"; // error
^ ~~~~~~~
Source.cpp:24:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from
'const char [6]' to 'const Name &' for 1st argument
class Name {
^
Source.cpp:26:5: note: candidate constructor not viable: no known conversion from 'const char [6]' to 'cstring' for 1st
argument
Name(cstring str)
^
1 error generated.
上述代码中,由于构造函数不显式,const char*
可以隐式转换为cstring
,cstring
也可以隐式转换Name
为 ;const char*
因此存在从到的转换序列Name
。那么为什么 Clang/GCC 不允许这样的复制初始化(msvc 允许这种情况)?