【发布时间】:2014-06-16 10:52:52
【问题描述】:
#include <string>
struct String
{
template<typename T> operator T*() { return 0; }
operator std::string() { return ""; }
};
int main()
{
String myStr;
std::string str1(myStr); // ambiguous, error C2668
std::string str2 = myStr; // error C2440:
// 'initializing' : cannot convert from 'String' to
// `std::basic_string<char,std::char_traits<char>,std::allocator<char>>',
// No constructor could take the source type,
// or constructor overload resolution was ambiguous
const std::string& rStr = myStr; // Ok, but why?
}
我正在使用 VS 2013。
问题:
为什么
str1和str2的定义会导致不同的编译错误?据我所知,在创建
rStr时,首先会创建一个临时字符串对象,然后rStr将引用该临时对象。但是,为什么临时对象的创建不会导致编译错误?tmp和strN有什么不同吗?
【问题讨论】:
-
据我所知,第二个错误是一个错误。 g++和clang++接受
str2的定义+初始化。
标签: c++ c++11 implicit-conversion