clang 和带有构造函数和 return 值的 microsoft c++/QT5 之间的不同行为
differnt behaviour between clang and microsoft c++/QT5 with constructors and return values
根据 Microsoft visual studio 2013(由 QT Creator、QT 5.4 构建),这段代码没问题:
#include <string>
struct X {
X(std::string const &) {};
};
X wibble() { return ""; }
clang 然而说
test.cpp(53) : error: no viable conversion from 'const char [1]' to 'X'
X wibble() { return ""; }
test.cpp(49) : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [1]' to 'const X &' for 1st argument
struct X {
test.cpp(49) : note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'const char [1]' to 'X &&' for 1st argument
struct X {
test.cpp(50) : note: candidate constructor not viable: no known conversion from 'const char [1]' to 'const std::string &' (aka 'const basic_string<char, char_traits<char>, allocator<char> > &') for 1st argument
X(std::string const &) {};
它与 QString 的价值相同。假设 clang 是正确的,为什么它会抱怨?
即使在MinGW
中也无法编译,因为它是非法的。因为只有一层用户定义的隐式转换是合法的。在您的代码中,您有 2 级转换:到 std::string
和到 X
.
struct X {
X( std::string const &) {}
};
X wibble1() { return ""; } // 2 level: error
X wibble2() { return X(""); } // 1 level: ok
即使在这里你也有同样的错误:
void foobar(X x) {
}
int main()
{
foobar(X(""));// ok, 1 level
foobar ("f");
// error: could not convert '(const char*)"f"' from 'const char*' to 'X'
}
根据 Microsoft visual studio 2013(由 QT Creator、QT 5.4 构建),这段代码没问题:
#include <string>
struct X {
X(std::string const &) {};
};
X wibble() { return ""; }
clang 然而说
test.cpp(53) : error: no viable conversion from 'const char [1]' to 'X'
X wibble() { return ""; }
test.cpp(49) : note: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [1]' to 'const X &' for 1st argument
struct X {
test.cpp(49) : note: candidate constructor (the implicit move constructor) not viable: no known conversion from 'const char [1]' to 'X &&' for 1st argument
struct X {
test.cpp(50) : note: candidate constructor not viable: no known conversion from 'const char [1]' to 'const std::string &' (aka 'const basic_string<char, char_traits<char>, allocator<char> > &') for 1st argument
X(std::string const &) {};
它与 QString 的价值相同。假设 clang 是正确的,为什么它会抱怨?
即使在MinGW
中也无法编译,因为它是非法的。因为只有一层用户定义的隐式转换是合法的。在您的代码中,您有 2 级转换:到 std::string
和到 X
.
struct X {
X( std::string const &) {}
};
X wibble1() { return ""; } // 2 level: error
X wibble2() { return X(""); } // 1 level: ok
即使在这里你也有同样的错误:
void foobar(X x) {
}
int main()
{
foobar(X(""));// ok, 1 level
foobar ("f");
// error: could not convert '(const char*)"f"' from 'const char*' to 'X'
}