加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将NULL作为对象返回时未收到任何警告

发布时间:2020-12-16 10:02:34 所属栏目:百科 来源:网络整理
导读:我不明白为什么我没有得到警告(用g或clang)来返回NULL作为下面的newtstr()中的对象: #includeiostreamusing namespace std;string newstr();int main(){ string s = newstr(); cout s endl; return 0;}string newstr(){ return NULL;} . $g++ -Wall -Wextra
我不明白为什么我没有得到警告(用g或clang)来返回NULL作为下面的newtstr()中的对象:

#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)).该行返回NULL;导致使用NULL指针作为参数对该构造函数进行隐式调用 – 这是有效代码,但显然无法正确运行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读