James Kanze
11/13/2008 9:37:00 PM
On Nov 13, 11:19 am, Rolf Magnus <ramag...@t-online.de> wrote:
> sanjay wrote:
> > ======================================
> > #include <iostream>
> > using namespace std;
> > int main()
> > {
> > void print(const string&);
> > print("hi");
> > print(NULL);
> > return 0;
> > }
> > void print(const string& s)
> > {
> > cout<<"s is "<<s<<endl;
> > }
> > ======================================
> > The above program compiles successfully but fails at run
> > time because NULL is passed as argument in the second call
> > to print.
> > Why doesn't the compiler give an error on passing of NULL
> > value?
> Well, semantically, NULL can be converted to std::string, just
> as "hi" can. How could the compiler know that NULL isn't a
> valid value?
Maybe we understand "semantically" differently, but I would say
that his problem is precisely that NULL can't be semantically
converted to an std::string. His code only compiles because it
is syntactically correct; he provides a value which can be
converted to type char const*, and that's all the compiler
checks. Semantically, of course, NULL isn't a string, in any
sense of the word, and it doesn't make sense to try to convert
it to a string. (In C, one might use it to indicate the absense
of a string; std::string doesn't support that concept, however.)
> > How could we check for such arguments in our program when we
> > are using strings?
> I don't see a way to do that, except for providing an overload
> of the function for const char*.
An implementation of std::string could easily cause it to
trigger a compiler error; just provide a private constructor
which takes some other type of pointer (which would make
std::string(NULL) ambiguous).
> The problem is that the error already manifests before print
> is even entered, in the constructor of std::string. BTW: The
> implementation I use throws an exception of type
> std::logic_error in this case, but I don't think that this is
> required by the standard.
It's undefined behavior. With a good implementation of
std::sttring, it won't compile. (Regretfully, I don't know of
any implementations which are good by that definition:-).
--
James Kanze (GABI Software) email:james.kanze@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