string.c_str是Borland封裝的String類中的一個函數,它返回當前字符串的首字符地址。
c_str函數的返回值是const char*的,不能直接賦值給char*,所以就需要我們進行相應的操作轉化。
~~~
#include <iostream>
#include <string>
int main() {
std::string s = "Chelse";
const char *str = s.c_str();
std::cout << str << std::endl;
s[1] = 'm';
std::cout << str << std::endl;
return 0;
}
~~~
第一個輸出 當然是 Chelse;
第二個輸出呢: Chelse還是Cmelse呢?
答案是Cmelse。
const char*的值應該是個常量啊,怎么還能改變值呢?
這就是很多人遇到的坑兒,也許面試的時候你會順利的回答出來,但是在實際的工程中,往往掉進坑兒里,難以自拔。
const char*, char const*, char* const的區別是什么?老
const char*與char const*是等價的,指的是指向字符常量的指針,即指針可以改變指向但其指向的內容不可以改變。
而char* const相反,指的是常量指針,即指向不可以改變但指針指向的內容可以改變。因此這里的const char*指向的內容本類是不可以改變的。
那么這里為什么改變了呢?這跟str這個const char*的生命周期及string類的實現有關,string的c_str()返回的指針是由string管理的,因此它的生命期是string對象的生命期,而string類的實現實際上封裝著一個char*的指針,而c_str()直接返回該指針的引用,因此string對象的改變會直接影響已經執行過的c_str()返回的指針引用。
看下官方說法:
~~~
const charT* c_str() const;
Returns: A pointer to the initial element of an array of length size() + 1 whose first size() elements equal the corresponding elements of the string controlled by *this and whose last element is a null character specified by charT().
Requires: The program shall not alter any of the values stored in the array. Nor shall the program treat the returned value as a valid pointer value after any subsequent call to a non-const member function of the class basic_string that designates the same object as this.
~~~
簡而言之,調用任何 std::string 的非 const 成員函數以后,c_str() 的返回值就不可靠了。
- 前言
- deprecated關鍵字
- 指針(內存泄露)
- 頭文件相互包含(Compiler error C2653: not a class or namespace name)
- 獲取一張圖片的width和height
- This function or variable may be unsafe.
- 智能指針陷阱
- string中的c_str()陷阱
- wstring與string的轉換
- windows下chrome瀏覽器插件不能安裝
- 重定義關鍵字
- 正確釋放vector的內存
- 獲取設備環境HDC
- 抽象類不能實例化對象(但是你明明定義的不是抽象類)
- 重載賦值運算符的自我賦值
- 程序中的變量未初始化
- 成對使用new和delete時要采取相同的形式
- 意想不到的除數為零
- map的初始化(插入數據)
- 正則表達式截取字符串
- 捕獲窗口之外的鼠標消息(鉤子還是??)
- 類中的靜態成員變量(static or const static)
- 有if就要有else(一定成對)
- map查找結果處理
- 使用using namespace std的壞習慣
- new一個指針數組、以及創建動態二維數組
- 使用太多的全局變量
- 沒有及時break出for循環
- vector使用erase后迭代器變成野指針
- C++函數的默認參數(重新定義默認參數)
- 0xC0000005: 讀取位置 xxx時發生訪問沖突
- std::string初始化、最快速判斷字符串為空
- 你開發的軟件安裝在C盤Program Files (x86)下產生的異常