给一个std :: string赋值一个nullptr是安全的? [英] Assign a nullptr to a std::string is safe?

查看:1104
本文介绍了给一个std :: string赋值一个nullptr是安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个小项目,发生以下情况:

  std :: string myString; 
#GetValue()返回一个char *
myString = myObject.GetValue();

我的问题是如果 GetValue() NULL myString 成为空字符串?是否未定义?或它会segfault?

解决方案

有趣的小问题。根据C ++ 11标准, 21.4.2.9,

  basic_string(const charT * s,const Allocator& a = Allocator()); 

必须:s不得为空指针。

由于标准不要求库在不满足特定要求时抛出异常,因此传递一个空指针会引发未定义的行为。


I was working on a little project and came to a situation where the following happened:

std::string myString;
#GetValue() returns a char*
myString = myObject.GetValue();

My question is if GetValue() returns NULL myString becomes an empty string? Is it undefined? or it will segfault?

解决方案

Interesting little question. According to the C++11 standard, sect. 21.4.2.9,

basic_string(const charT* s, const Allocator& a = Allocator());

Requires: s shall not be a null pointer.

Since the standard does not ask the library to throw an exception when this particular requirement is not met, it would appear that passing a null pointer provoked undefined behavior.

这篇关于给一个std :: string赋值一个nullptr是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆