可以为 NULL 的 C++ 字符串 [英] C++ string that can be NULL

查看:81
本文介绍了可以为 NULL 的 C++ 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在我的 C++ 应用程序中传递这样的字符串:

I'm used to passing around string like this in my C++ applications:

void foo(const std::string& input)
{
  std::cout << input.size() << std::endl;
}

void bar()
{
  foo("stackoverflow");
}

现在我希望字符串为 NULL:

Now I have a case where I want the string to be NULL:

void baz()
{
  foo("stackoverflow");
  foo(NULL); // very bad with foo implementation above
}

我可以将 foo 改为:

void foo(const std::string* input)
{
  // TODO: support NULL input
  std::cout << input->size() << std::endl;
}

但是要传递字符串文字或将 char* 复制到 foo 的实现中,我需要编写如下内容:

But to pass a string literal or copy a char* to that implementation of foo I need to write something like this:

void bar()
{
  string input("hi"); // annoying temporary
  foo(&input);
  foo(NULL);  // will work as long as foo handles NULL properly
}

我开始考虑从 std::string 继承并添加一个 null 属性,但我不确定这是个好主意.也许对可以为 NULL 的参数简单地使用 const char* 字符串更好,但是如果我想保存字符串(或 NULL)的副本而不必自己管理其内存怎么办?(参见 使用的一些缺点是什么?C 风格的字符串? 等)

I started thinking about inheriting from std::string and adding a null property, but I'm not so sure it's a good idea. Maybe it is better to simply use a const char* string for parameters that can be NULL, but what if I want to save a copy of the string (or NULL) without having to manage its memory myself? (See What are some of the drawbacks to using C-style strings? etc.)

周围有什么聪明的解决方案吗?

Any clever solution around?

推荐答案

如果您希望类型为 null,则将其设为指针.传递字符串指针而不是引用,因为这正是指针可以做的,而引用不能.引用总是指向同一个有效对象.指针可以设置为空,或重新定位以指向另一个对象.因此,如果您需要指针可以做的事情,请使用指针.

If you want the type to be null, then make it a pointer. Pass string pointers around instead of references, since this is precisely what pointers can do, and references cant. References always point to the same valid object. Pointers can be set to null, or be reseated to point to another object. Thus, if you need the things pointers can do, use pointers.

或者,使用 boost::optional,它允许以更类型安全的方式指定此变量可能包含也可能不包含值".

Alternatively, use boost::optional, which allows a more type-safe way to specify "this variable may or may not contain a value".

或者,当然,更改语义以便您使用空字符串而不是 null,传递一个单独的 bool 参数指定字符串是否可用,或者重构以便您首先不需要它.

Or, of course, change the semantics so you either use empty strings instead of null, pass a separate bool parameter specifying whether the string is available or not, or refactor so you don't need this in the first place.

这篇关于可以为 NULL 的 C++ 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆