用字符串参数传递char *报告错误调用构造函数错误
template<typename T>
class SharedValue {
public:
SharedValue(const T& t): valuePtr(new T(t)) {}
const SharedValue& operator = (const T &t) {
*valuePtr = t;
return *this;
}
protected:
dd_shared_ptr<T> valuePtr;
};
typedef SharedValue<std::string> SharedString;
int main(int argc, const char * argv[]) {
// compile succeeded
SharedString str(argv[0]);
// compile failed:
SharedString str2 = argv[0];
return 0;
}
str2
施工失败,报告:
没有可行的转换从'const char *'到'sharedString'(aka'sharedValue&lt; basic_string&lt; char,char_traits&lt; char&gt; char&gt; char&lt; char&lt;
为什么str
成功了,而str2
失败了,有区别吗?
template<typename T>
class SharedValue {
public:
SharedValue(const T& t): valuePtr(new T(t)) {}
const SharedValue& operator = (const T &t) {
*valuePtr = t;
return *this;
}
protected:
dd_shared_ptr<T> valuePtr;
};
typedef SharedValue<std::string> SharedString;
int main(int argc, const char * argv[]) {
// compile succeeded
SharedString str(argv[0]);
// compile failed:
SharedString str2 = argv[0];
return 0;
}
The str2
construction failed, reporting:
No viable conversion from 'const char *' to 'SharedString' (aka 'SharedValue<basic_string<char, char_traits<char>, allocator<char>>>')
Why str
succeeded whereas str2
failed, is there any difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,两者之间存在区别。特别是,在
str
中,我们具有直接初始化,而在str2
中,我们复制初始化。可以从复制初始化文档指出:
(强调我的)
现在,让我们以情况为基础将其应用于给定的示例。
案例1
在这里我们考虑以下陈述:
上述复制初始化。并且由于
共享string
不能直接从右侧的 initializer const char*在右侧产生,因为它需要隐含的转换,该案例1不允许按照上述报价陈述。情况2
在这里我们考虑以下陈述:
虽然上述使用直接初始化,并且由于有一个隐式转换可用(使用转换构造函数),,这次是根据上述语句允许的。
Yes, there is difference between the two. In particular, in
str
we have have direct initialization while instr2
we have copy initialization.The behavior of your program can be understood from copy initialization documentation which states:
(emphasis mine)
Now let's apply this to your given example on case by case basis.
Case 1
Here we consider the statement:
The above uses copy initialization. And as
SharedString
can't be directly produced from the initializer of typeconst char*
on the right hand side since it requires an implicit conversion, this case 1 isn't allowed in accordance with the above quoted statement.Case 2
Here we consider the statement:
while the above uses direct initialization and since there is an implicit conversion available(using the converting constructor), this time it is allowed according to the above quoted statement.