【问题标题】:How to allow a std:string parameter to be NULL?如何允许 std:string 参数为 NULL?
【发布时间】:2011-07-30 16:00:23
【问题描述】:

我有一个函数 foo(const std::string& str);,如果你使用 foo(NULL) 调用它,它确实会崩溃。

我能做些什么来防止它崩溃?

【问题讨论】:

  • 你用 str 里面的 foo 做什么?如果您测试 str 是否为 NULL 并从函数中正常退出,它不应该崩溃。
  • 你得到了一些有用的建议,但你确定你正在接近这个权利吗?你为什么使用指针? std::string (和引用)的部分优点是您不必弄乱指针。 (通常)
  • 这也是臭名昭著的std::string s(false)事情的原因。
  • “医生,医生,我这样做的时候好痛!” ;-)

标签: c++ std


【解决方案1】:

std::string 有一个带有 const char* 参数的构造函数。当你将 NULL 传递给它时,它的构造函数会崩溃,而当你写 foo(NULL) 时,这个构造函数会被隐式调用。

我能想到的唯一解决方案是重载 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
}

【讨论】:

  • +1。在@James McNellis 正确指出我不知何故忽略了关键点之后,我删除了自己的回复......
【解决方案2】:

你可以使用Boost.Optional

#include <boost/optional.hpp>
#include <string>

using namespace std;
using namespace boost;

void func(optional<string>& s) {
    if (s) {  // implicitly converts to bool
        // string passed in
        cout << *s << endl; // use * to get to the string
    } else {
        // no string passed in
    }
}

用字符串调用它:

string s;
func(optional<string>(s));

并且没有字符串:

func(optional<string>());

Boost.Optional 为您提供了一种类型安全的方法来获得可为空的值,而无需求助于指针及其相关问题。

【讨论】:

【解决方案3】:

您有一个接受std::string 的函数,因此请为其提供std::string,而不是指针。

foo(std::string());

这将为函数提供一个空字符串,这可能就是您无论如何都会解释您的 null 值的内容。

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 2013-09-07
    • 2014-06-10
    • 1970-01-01
    • 2018-03-09
    • 2015-06-29
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多