请教下: 如下代码, 将传给函数foo(string str)会有问题吗? 但是我在这里产生了core,确实实在不理解为什么。
void foo(string str) {
}
int main(){
const char* buf = "hello";
foo(buf);
return 0;
}
我的理解是不会有问题,因为将const char buf传进函数foo时会隐式调用string的构造函数string(char str)将const char* buf构造成字符串string str后再在函数foo内使用。
在gcc-8.2/gcc-8.2/include/c++/8.2.0/bits/basic_string.tcc +664中,显示会获取char*的长度:traits_type::length(__s)。所以更加验证了这种隐式转换不会有问题。
// TBD: DPG annotate
template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT, _Traits, _Alloc>::
basic_string(const _CharT* __s, const _Alloc& __a)
: _M_dataplus(_S_construct(__s, __s ? __s + traits_type::length(__s) :
__s + npos, __a), __a)
{ }