c ++ - 为字符串分配空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11617552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ - Assigning null to a string
提问by Maria
I am learning C++ on my own. I have the following code but it gives error.
我正在自学 C++。我有以下代码,但它给出了错误。
#include <iostream>
#include <string>
using namespace std;
int setvalue(const char * value)
{
string mValue;
if(value!=0)
{
mValue=value;
}
else
{
mValue=0;
}
}
int main ()
{
const char* value = 0;
setvalue(value);
cin.get();
return 0;
}
So want to create a function which accepts char pointers and I want to pass a pointer to it. The function assigns the pointer to its member variable. I'm passing a null pointer intentionally. Following is the error I'm getting:
所以想创建一个接受字符指针的函数,我想传递一个指针给它。该函数将指针分配给其成员变量。我故意传递一个空指针。以下是我得到的错误:
D:\CPP\TestCP.cpp In function `int setvalue(const char*)':
note C:\Dev-Cpp\include\c++.4.2\bits\basic_string.h:422 candidates are: std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
note C:\Dev-Cpp\include\c++.4.2\bits\basic_string.h:422 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
note C:\Dev-Cpp\include\c++.4.2\bits\basic_string.h:422 std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
it's basically complaining about line: mValue=0;
它基本上是在抱怨 line: mValue=0;
Why is it complaining about this line? I can't assign a null to a String?
为什么抱怨这条线?我不能为字符串分配空值?
回答by James McNellis
I can't assign a null to a String?
我不能为字符串分配空值?
No. std::stringis not a pointer type; it cannot be made "null." It cannot represent the absence of a value, which is what a null pointer is used to represent.
No. std::string不是指针类型;它不能被设为“空”。它不能表示没有值,而这正是空指针用来表示的。
It can be made empty, by assigning an empty string to it (s = ""or s = std::string()) or by clearing it (s.clear()).
通过为其分配一个空字符串(或)或清除它(),可以将其设为空。s = ""s = std::string()s.clear()
回答by templatetypedef
You cannot assign NULLor 0to a C++ std::stringobject, because the object is not a pointer. This is one key difference from C-style strings; a C-style string can either be NULLor a valid string, whereas C++ std::strings always store some value.
您不能将NULL或分配0给 C++std::string对象,因为该对象不是指针。这是与 C 风格字符串的主要区别之一;C 风格的字符串可以是NULL一个有效的字符串,而 C++ std::strings 总是存储一些值。
There is no easy fix to this. If you'd like to reserve a sentinel value (say, the empty string), then you could do something like
对此没有简单的解决方法。如果你想保留一个哨兵值(比如空字符串),那么你可以做类似的事情
const std::string NOT_A_STRING = "";
mValue = NOT_A_STRING;
Alternatively, you could store a pointer to a string so that you can set it to null:
或者,您可以存储一个指向字符串的指针,以便将其设置为 null:
std::string* mValue = NULL;
if (value) {
mValue = new std::string(value);
}
Hope this helps!
希望这可以帮助!
回答by Juraj Blaho
Literal 0is of type intand you can't assign intto std::string. Use mValue.clear()or assign an empty string mValue="".
文字0是类型int,您不能分配int给std::string. 使用mValue.clear()或分配一个空字符串mValue=""。
回答by David Cormack
There are two methods to consider which achieve the same effect for handling null pointers to C-style strings.
有两种方法可以考虑实现相同的效果来处理指向 C 样式字符串的空指针。
The ternary operator
三元运算符
void setvalue(const char *value)
{
std::string mValue = value ? value : "";
}
or the humble if statement
或谦虚的 if 语句
void setvalue(const char *value)
{
std::string mValue;
if(value) mValue = value;
}
In both cases, valueis only assigned to mValuewhen valueis nota null pointer. In all other cases (i.e. when valueisnull), mValuewill contain an empty string.
在这两种情况下,value只分配到mValue的时候value是不是一个空指针。在所有其他情况下(即当value为空时),mValue将包含一个空字符串。
The ternary operator method may be useful for providing an alternative default string literal in the absence of a value from value:
三元运算符方法可用于在没有值的情况下提供替代的默认字符串文字value:
std::string mValue = value ? value : "(NULL)";
回答by monkey0506
I won't argue that it's a goodidea (or the semantics of using nullptrwith things that aren't pointers), but it's relatively simple to create a class which would provide "nullable" semantics (see nullable_string).
我不会争辩说这是一个好主意(或nullptr与不是指针的事物一起使用的语义),但创建一个提供“可为空”语义的类相对简单(请参阅nullable_string)。
However, this is a much better fit for C++17's std::optional:
但是,这更适合 C++17 的std::optional:
#include <string>
#include <iostream>
#include <optional>
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b)
{
if (b)
return "Godzilla";
else
return {};
}
int main()
{
std::cout << "create(false) returned "
<< create(false).value_or("empty") << std::endl;
// optional-returning factory functions are usable as conditions of while and if
if (auto str = create(true))
{
std::cout << "create(true) returned " << *str << std::endl;
}
}
std::optional, as shown in the example, is convertible to bool, or you may use the has_value()method, has exceptions for bad access, etc. This provides you with nullable semantics, which seems to be what Mariawas trying to accomplish.
std::optional,如示例中所示,可转换为bool,或者您可以使用该has_value()方法,具有访问错误的异常等。这为您提供了可为空的语义,这似乎是Maria试图完成的。
And if you don't want to wait around for C++17 compatibility, see this answer about Boost.Optional.
如果您不想等待 C++17 兼容性,请参阅有关 Boost.Optional 的答案。
回答by Robert Calhoun
Many C APIs use a null pointer to indicate "use the default", e.g. mosquittopp. Here is the pattern I am using, based on David Cormack's answer:
许多 C API 使用空指针来指示“使用默认值”,例如mosquittopp。这是我使用的模式,基于David Cormack的回答:
mosqpp::tls_set(
MqttOptions->CAFile.length() > 0 ? MqttOptions->CAFile.c_str() : NULL,
MqttOptions->CAPath.length() > 0 ? MqttOptions->CAPath.c_str() : NULL,
MqttOptions->CertFile.length() > 0 ? MqttOptions->CertFile.c_str() : NULL,
MqttOptions->KeyFile.length() > 0 ? MqttOptions->KeyFile.c_str() : NULL
);
It is a little cumbersome, but allows one to keep everything as a std::stringup until the API call itself.
这有点麻烦,但允许std::string在 API 调用本身之前将所有内容保持原样。
回答by Susheel Dwivedi
compiler gives error because when assigning mValue=0 compiler find assignment operator=(int ) for compile time binding but it's not present in the string class. if we type cast following statement to char like mValue=(char)0 then its compile successfully because string class contain operator=(char) method.
编译器给出错误,因为在分配 mValue=0 编译器时找到赋值 operator=(int ) 进行编译时绑定,但它不存在于字符串类中。如果我们将下面的语句类型转换为像 mValue=(char)0 这样的 char 则它编译成功,因为字符串类包含 operator=(char) 方法。
回答by Naveen
The elsecase is unncecessary, when you create a stringobject it is empty by default.
这种else情况是不必要的,当您创建一个string对象时,默认情况下它是空的。

