簡體   English   中英

字符串類中c_str函數的內存分配

[英]memory allocation for c_str function in string class

我有一個類的成員函數,如下所述

int x(std::string &a, std::string &b) {
    char *ptr = another_member.getStringMember().c_str() //I am storing the pointer 
    cout << ptr << endl;
    a="hello";
    cout << ptr << endl; 
}

輸出是

StringMember

你好

你能解釋一下為什么會這樣嗎? 謝謝

很可能因為another_member.getStringMembera是相同的字符串。

在這種情況下,在使用a="hello";修改字符串后使用ptr實際上是不合法的a="hello"; 因為變異操作可以使先前獲得的指針無效。

只是出於好奇,你打電話

x(another_member.getStringMember, fooBar);

c_str()返回字符串對象的內部指針,一旦修改源字符串,它就會變為無效

a="hello"行之后,你不能保證ptr仍然可用(因為看起來它們是相同的字符串)。 在您的情況下,由於Hello較小,並且字符串未被共享,因此看起來它重用了空間。

這是特定於實現的行為。 它可能很容易崩潰。

執行該行后,來自another_member.getStringElement()的temp std :: string超出范圍。 更改

char *ptr = another_member.getStringMember().c_str();

std::string s = another_member.getStringMember();
const char *ptr = s.c_str();

你的意思是對another_member.getStringElement().c_str()執行another_member.getStringElement().c_str() another_member.getStringElement.c_str()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM