2016-04-24 177 views
3

我不明白为什么我没有得到一个警告(使用g ++或铛++)在下面newtstr()返回NULL作为对象没有得到任何警告。NULL返回时为对象

$ g++ -Wall -Wextra -pedantic testptr.cpp 
$ 

我做的,但是,得到一个运行时错误:

$ ./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 
+0

你已经标记了这个铿锵声++。这是否也适用于铿锵声? –

+1

你为什么期待警告?这是一个有效的构造。 – ZDF

+0

@ZDF OP或者不知道隐式的'const char *'强制转换,或者他期望他的编译器看到“嘿,这是一个静态表达式,它给了我一个零指针,'string'ctor试图做的东西,它应该能够警告我这件事!“ –

回答

7

std::string具有constructorbasic_string(const CharT* s, const Allocator& alloc = Allocator());它接受一个const char*指针用于构造一个新的字符串(参见(5))。行return NULL;导致隐式调用该构造函数与NULL指针作为参数 - 这是有效的代码,但显然将无法正常运行。

+0

啊 - 谢谢!我认为这属于“有很多烘焙到C++标准库”类别... –

+0

不是真的,@ChrisGregg。想象一个没有方法从C风格的字符串(它是一个'const char'数组,它对所有方法调用本质上转换为'const char *')构造'std :: string'的方法 - d很难在你的代码中指定字符串,因为你的普通''text''字符串就是--C风格的字符串。 –