Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Assigning null to a std::string

I am learning C++ on my own. I have the following code but it gives error.

#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++\3.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++\3.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++\3.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;

Why is it complaining about this line? I can't assign a null to a String?

like image 358
Maria Avatar asked Jul 23 '12 17:07

Maria


People also ask

How do I assign a null to a string in C++?

We can do this using the std::string::clear function. It helps to clear the whole string and sets its value to null (empty string) and the size of the string becomes 0 characters. string::clear does not require any parameters, does not return any error, and returns a null value.

Can std::string contain null?

Yes you can have embedded nulls in your std::string .

How do you make a string null?

KennyTM mentioned just setting the first character to '\0' with str[0] = '\0'; , which doesn't clear every byte but does mark the string as having zero length. There is also memset() which is used to fill a block of memory with any arbitrary value, and 0 is certainly allowed.


1 Answers

I can't assign a null to a String?

No. std::string is 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.

It can be made empty, by assigning an empty string to it (s = "" or s = std::string()) or by clearing it (s.clear()).

like image 186
James McNellis Avatar answered Oct 05 '22 04:10

James McNellis