return 0 for std::string type


#include <string>

std::string test()
  return 0;

int main()
  return 0;

這樣子會compile過嗎? 答案是可以,此範例是可以通過compile。但是0是integer,integer和string應該不相容吧? 的確是不相容,其他的integer會compile不過,剛好 0 例外,在 C++11 4.10描述了 null pointer constant可以被轉成 null pointer

答案是可以,原因就在 std::string 接收 implicit construct from char pointer

A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to
zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type

C++11 § 4.10 Pointer conversions

所以結果就是 std::string constructor看到null pointer,根據 C++11,描述

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

Requires: s shall not be a null pointer.

C++11 §

標準要求,不可以傳null pointer進去,否則可能是直接abort,可能是exception,結果為UB

This entry was posted in C++ Language. Bookmark the permalink.

Leave a Reply