問題描述
下面函數返回的指針是否有效?
Is the pointer returned by the following function valid?
const char * bool2str( bool flg )
{
return flg ? "Yes" : "No";
}
它在 Visual C++ 和 g++ 中運行良好.C++ 標準對此有何評論?
It works well in Visual C++ and g++. What does C++ standard say about this?
推薦答案
關于存儲時長:
2.13.4普通字符串文字和 UTF-8 字符串文字也稱為窄字符串文字.一個箭頭字符串文字的類型為n const char 數組",其中 n 是如下定義的字符串大小,并且具有靜態存儲時長
2.13.4 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type "array of n const char", where n is the size of the string as defined below, and has static storage duration
結合3.7.1閱讀
3.7.1.
所有沒有動態存儲期,沒有線程存儲期,并且是非本地有靜態存儲期限.這些物品的儲存應持續到程序 (3.6.2, 3.6.3).
All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3).
類型:
附件 C
第 2.13.4 條:
更改:字符串文字變為 const字符串文字的類型從char 數組"更改為const char 數組".的類型char16_t 字符串文字從某種整數類型的數組"更改為const char16_t 的數組".這char32_t 字符串文字的類型從某個整數類型的數組"更改為const char32_- 的數組"噸."寬字符串字面量的類型從wchar_t 數組"更改為const wchar_t 數組".
Change: String literals made const The type of a string literal is changed from "array of char " to "array of const char." The type of a char16_t string literal is changed from "array of some-integer-type " to "array of const char16_t." The type of a char32_t string literal is changed from "array of some-integer-type " to "array of const char32_- t." The type of a wide string literal is changed from "array of wchar_t " to "array of const wchar_t."
基本原理:這避免調用不適當的重載函數,該函數可能期望能夠修改它的參數.
Rationale: This avoids calling an inappropriate overloaded function, which might expect to be able to modify its argument.
對原始特征的影響: 改變定義好的特征的語義.轉換難度:簡單的句法轉換,因為字符串文字可以轉換為字符*;(4.2).最常見的情況由新的但不推薦使用的標準轉換處理:char* p = "abc";//在 C 中有效,在 C++ 中不推薦使用字符* q = expr ?"abc" : "de";//在 C 中有效,在 C++ 中無效
Effect on original feature: Change to semantics of well-defined feature. Difficulty of converting: Simple syntactic transformation, because string literals can be converted to char*; (4.2). The most common cases are handled by a new but deprecated standard conversion: char* p = "abc"; // valid in C, deprecated in C++ char* q = expr ? "abc" : "de"; // valid in C, invalid in C++
使用范圍:有正當理由將字符串文字視為潛在指針的程序可修改的內存可能很少見.
How widely used: Programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are probably rare.
動態分配(標準中AFAIK內存區域的上下文中永遠不會使用堆"這個詞)內存需要一個函數調用,該函數調用可能早在靜態內存之后的main
發生已分配.
Dynamically allocated (the word 'heap' is never used in context of an area of memory AFAIK in the standard) memory requires a function call that can happen as early as main
much after the static memory is allocated.
這篇關于函數返回后,指向字符串文字的指針是否仍然有效?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!