返回 NULL 作为对象时没有收到任何警告
Not getting any warning when returning NULL as object
我不明白为什么我在下面的 newtstr()
中没有收到警告(使用 g++ 或 clang++)将 NULL 作为对象返回:
#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
$
但是,我收到运行时错误:
$ ./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
有一个 constructor basic_string( const CharT* s, const Allocator& alloc = Allocator() );
,它接受一个 const char*
指针来构造一个新字符串(参见 (5))。 return NULL;
行导致以 NULL 指针作为参数隐式调用该构造函数 - 这是有效代码,但显然不会 运行 正确。
我不明白为什么我在下面的 newtstr()
中没有收到警告(使用 g++ 或 clang++)将 NULL 作为对象返回:
#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
$
但是,我收到运行时错误:
$ ./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
有一个 constructor basic_string( const CharT* s, const Allocator& alloc = Allocator() );
,它接受一个 const char*
指针来构造一个新字符串(参见 (5))。 return NULL;
行导致以 NULL 指针作为参数隐式调用该构造函数 - 这是有效代码,但显然不会 运行 正确。