如何允许std:string参数为NULL? [英] How to allow a std:string parameter to be NULL?
本文介绍了如何允许std:string参数为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
foo(const std :: string& str);
它会崩溃,如果你调用它使用 foo
我可以如何防止它崩溃?
方案 std :: string有一个构造函数,它接受一个const char *参数。当你向它传递NULL时,构造函数会崩溃,并且当你写foo(NULL)时,构造函数被隐式调用。
我可以想到的唯一解决方案是重载foo
void foo(const std :: string& str)
{
// function
}
void foo(const char * cstr)
{
if(cstr == NULL)
// do something
else
foo(std :: string(cstr)); // call regular funciton
}
I have a function foo(const std::string& str);
that it does crash if you call it using foo(NULL)
.
What can I do to prevent it from crashing?
解决方案 std::string has a constructor that takes a const char* parameter. That's constructor is going to crash when you pass NULL to it, and that constructor is called implicitly when you write foo(NULL).
The only solution I can think of is to overload foo
void foo(const std::string& str)
{
// your function
}
void foo(const char* cstr)
{
if (cstr == NULL)
// do something
else
foo(std::string(cstr)); // call regular funciton
}
这篇关于如何允许std:string参数为NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文