Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not getting any warning when returning NULL as object

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
like image 611
Chris Gregg Avatar asked Nov 16 '25 12:11

Chris Gregg


1 Answers

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.

like image 102
Unimportant Avatar answered Nov 19 '25 01:11

Unimportant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!