473,395 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Empty pointer to std::string

Hi!

I just found something interesting.
I mean what do you think about this:

char *p = 0;
std::string str = p;

Why std::string doesn't check null pointers?

Why not doin' some checking:

class String : public std::string
{
public:
String():std::string() {}
String(const char *str):std::string() {
if(str == 0)
*this = std::string();
else
*this = std::string(str);
}
String(const std::string& str):std::string(str) {}
};

This is only an example, 'cause i didn't want to write from scratch
string class, so i just derived. :)

Apr 4 '07 #1
10 7275
mr_sorcerer wrote:
Hi!

I just found something interesting.
I mean what do you think about this:

char *p = 0;
std::string str = p;

Why std::string doesn't check null pointers?
Because the standard prefers undefined behavior to wasting CPU cycles.

Why not doin' some checking:

class String : public std::string
{
public:
String():std::string() {}
String(const char *str):std::string() {
if(str == 0)
*this = std::string();
else
*this = std::string(str);
}
String(const std::string& str):std::string(str) {}
};

This is only an example, 'cause i didn't want to write from scratch
string class, so i just derived. :)
Feel free to do that. I would prefer an assert( str != 0 ). That way, I
would use String for testing and could replace it with std::string when I
am convinced that I avoided UB successfully.

BTW: I find it is somewhat neat to have a namespace debug that provides
debug::vector<>, debug::string, ... with defined behavior (assert) instead
of UB.
Best

Kai-Uwe Bux
Apr 4 '07 #2
On Wed, 04 Apr 2007 06:24:40 -0400, Kai-Uwe Bux wrote:
>mr_sorcerer wrote:
>I just found something interesting.
I mean what do you think about this:

char *p = 0;
std::string str = p;

Why std::string doesn't check null pointers?

Because the standard prefers undefined behavior to wasting CPU cycles.
OTOH, a public member function should validate input. I'd consider
that good style.
>BTW: I find it is somewhat neat to have a namespace debug that provides
debug::vector<>, debug::string, ... with defined behavior (assert) instead
of UB.
assert is en-/disabled by the NDEBUG #define. assert uses 'namespace
NDEBUG' ;-)
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 4 '07 #3
Roland Pibinger wrote:
On Wed, 04 Apr 2007 06:24:40 -0400, Kai-Uwe Bux wrote:
>>mr_sorcerer wrote:
>>I just found something interesting.
I mean what do you think about this:

char *p = 0;
std::string str = p;

Why std::string doesn't check null pointers?

Because the standard prefers undefined behavior to wasting CPU cycles.

OTOH, a public member function should validate input. I'd consider
that good style.
True, but that is a quality of implementation issue. The standard does no
require public member functions of standard containers to do any of that.
Of course, you could just purchase / implement and then use a standard
library implementation that includes the assert() statements you want.

>>BTW: I find it is somewhat neat to have a namespace debug that provides
debug::vector<>, debug::string, ... with defined behavior (assert) instead
of UB.

assert is en-/disabled by the NDEBUG #define. assert uses 'namespace
NDEBUG' ;-)
Yes. However, that only works if you are using an standard library
implementation that does input validation, range checking, and so on.
Otherwise, you have to roll your own code.
Best

Kai-Uwe Bux
Apr 4 '07 #4
On Apr 4, 12:24 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
mr_sorcerer wrote:
I just found something interesting.
I mean what do you think about this:
char *p = 0;
std::string str = p;
Why std::string doesn't check null pointers?
Because the standard prefers undefined behavior to wasting CPU cycles.
Because the standard prefers to leave the choice up to the
implementors, so they can do whatever is best for their
customers. (The systems I use all *do* check, and the above
code will systematically generate a core dump.)
Why not doin' some checking:
Most systems do. There's usually no need for explicit checking,
of course, because the hardware does it implicitly,
automatically. But the result is the same: you get a core dump
(or the equivalent), which is the desired behavior in case of
programmer error.
class String : public std::string
{
public:
String():std::string() {}
String(const char *str):std::string() {
if(str == 0)
*this = std::string();
else
*this = std::string(str);
}
No. A null pointer is *not* an empty string. If you need to
support null values, you need something like Fallible (although
the names of the functions and the behavior in the invalid case
should probably be different).
String(const std::string& str):std::string(str) {}
};
This is only an example, 'cause i didn't want to write from scratch
string class, so i just derived. :)
Feel free to do that. I would prefer an assert( str != 0 ).
Why? On most platforms, the only thing that will buy you is a
different error message. I can't imagine an implementation of
std::string which doesn't access the pointer in the constructor,
and accessing a null pointer is a certain core dump under Unix
or Windows.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 5 '07 #5
On Apr 4, 5:11 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
Yes. However, that only works if you are using an standard library
implementation that does input validation, range checking, and so on.
Both VC++ and g++ do. If you're developping under Windows, you
certainly have access to VC++ (it's free), and if you're
developping under Unix, you certainly have access to g++ (also
free). Even if your final target compiler is something else,
there's nothing to stop you from using one of these compilers
during development.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 5 '07 #6
On 5 Apr 2007 01:47:36 -0700, "James Kanze" wrote:
>On Apr 4, 12:24 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
>mr_sorcerer wrote:
Why std::string doesn't check null pointers?
>Because the standard prefers undefined behavior to wasting CPU cycles.
Why not doin' some checking:

Most systems do. There's usually no need for explicit checking,
of course, because the hardware does it implicitly,
automatically. But the result is the same: you get a core dump
(or the equivalent), which is the desired behavior in case of
programmer error.
One 'expected' behavior would be a null_pointer_exception (derived
from std::runtime_error).
>No. A null pointer is *not* an empty string.
Although a null pointer is not an empty string it could be converted
to an empty string by a constructor. This is not elegant but makes
sense for strings (not for other types).

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 5 '07 #7
In article <46**************@news.utanet.at>,
Roland Pibinger <rp*****@yahoo.comwrote:
>On 5 Apr 2007 01:47:36 -0700, "James Kanze" wrote:
>>On Apr 4, 12:24 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
>>mr_sorcerer wrote:
Why std::string doesn't check null pointers?
>>Because the standard prefers undefined behavior to wasting CPU cycles.
>Why not doin' some checking:

Most systems do. There's usually no need for explicit checking,
of course, because the hardware does it implicitly,
automatically. But the result is the same: you get a core dump
(or the equivalent), which is the desired behavior in case of
programmer error.

One 'expected' behavior would be a null_pointer_exception (derived
from std::runtime_error).
>>No. A null pointer is *not* an empty string.

Although a null pointer is not an empty string it could be converted
to an empty string by a constructor.
True, but...
>This is not elegant but makes
sense for strings (not for other types).
....be careful with that kind of suggestion.
Which I'm certain is part of James's point.
--
Greg Comeau / 4.3.9 with C++0xisms now in beta!
Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Apr 5 '07 #8
Roland Pibinger wrote:
:: On 5 Apr 2007 01:47:36 -0700, "James Kanze" wrote:
::: On Apr 4, 12:24 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
:::: mr_sorcerer wrote:
::::: Why std::string doesn't check null pointers?
:::
:::: Because the standard prefers undefined behavior to wasting CPU
:::: cycles.
:::
::::: Why not doin' some checking:
:::
::: Most systems do. There's usually no need for explicit checking,
::: of course, because the hardware does it implicitly,
::: automatically. But the result is the same: you get a core dump
::: (or the equivalent), which is the desired behavior in case of
::: programmer error.
::
:: One 'expected' behavior would be a null_pointer_exception (derived
:: from std::runtime_error).

And that would be extremely expensive on platforms without hardware support.
Those platforms are often the ones where you cannot afford the performance
loss.
Bo Persson
Apr 5 '07 #9
On Apr 5, 11:35 am, rpbg...@yahoo.com (Roland Pibinger) wrote:
On 5 Apr 2007 01:47:36 -0700, "James Kanze" wrote:
On Apr 4, 12:24 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
mr_sorcerer wrote:
Why std::string doesn't check null pointers?
Because the standard prefers undefined behavior to wasting CPU cycles.
Why not doin' some checking:
Most systems do. There's usually no need for explicit checking,
of course, because the hardware does it implicitly,
automatically. But the result is the same: you get a core dump
(or the equivalent), which is the desired behavior in case of
programmer error.
One 'expected' behavior would be a null_pointer_exception (derived
from std::runtime_error).
So that the error can be hidden, and not show up immediately. I
wouldn't use such a class in production software.
No. A null pointer is *not* an empty string.
Although a null pointer is not an empty string it could be converted
to an empty string by a constructor.
Certainly. You can convert anything to anything with a suitable
constructor.

Whether it makes sense or not is another question.
This is not elegant but makes
sense for strings (not for other types).
Are you saying that NULL and "" are the same thing in C? I've
certainly never used them for the same thing in C, and when I
need the equivalent of a C function which returns a char const*
which can be null, in C++, I use Fallible< std::string >. An
empty string is NOT a null value (as anyone who has ever used a
data base can tell you).

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 5 '07 #10
Roland Pibinger wrote:

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady
Booch
A small (but important) technical note. The proper separator for .sigs
is "-- " (dash dash space). Yours is missing the space. Correct
separators allow newsreaders to auto-trim signatures.

Brian
Apr 5 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while(...
3
by: Old Wolf | last post by:
Is this undefined behaviour: #include <string> #include <vector> #include <algorithm> int main() { std::string s; char buf;
22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
19
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not...
8
by: Patrick Kowalzick | last post by:
Dear NG, I would like to change the allocator of e.g. all std::strings, without changing my code. Is there a portable solution to achieve this? The only nice solution I can think of, would be...
11
by: Dan Bass | last post by:
which one do you use and why? MyString == null || MyString == "" vs MyString == null || MyString.Length == 0
3
by: Rico | last post by:
If there are consecutive occurrences of characters from the given delimiter, String.Split() and Regex.Split() produce an empty string as the token that's between such consecutive occurrences. It...
26
by: Neville Lang | last post by:
Hi all, I am having a memory blank at the moment. I have been writing in C# for a number of years and now need to do something in VB.NET, so forgive me such a primitive question. In C#, I...
3
by: arnuld | last post by:
#include <iostream> #include <limits> int main() { std::string s1; std::cout << s1 << std::endl; return 0;
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.