I don't understand why I don't get a warning (with g++ or clang++) for returning a NULL as an object in newtstr() below:
#include<iostream>
using namespace std;
string newstr();
int main()
{
string s = newstr();
cout << s << endl;
return 0;
}
string newstr()
{
return NULL;
}
.
$ g++ -Wall -Wextra -pedantic testptr.cpp
$
I do, however, get a runtime error:
$ ./a.out
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted
$
.
$ g++ --version
g++ (GCC) 4.8.0
std::string has a constructor basic_string( const CharT* s, const Allocator& alloc = Allocator() ); which accepts a const char* pointer for constructing a new string (see (5)). The line return NULL; results in a implicit call to that constructor with a NULL pointer as argument - which is valid code but obviously won't run correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With