开发者

memory allocation for c_str function in string class

I have a member function of a class which is defined below, say

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; 
}

The output is

StringMember

Hello

Can you please explain why this开发者_如何学编程 happens ?? Thanks


Most likely because another_member.getStringMember and a are the same string.

In this case it is not actually legal to use ptr after the string has been modified with a="hello"; because mutating operations can make the previously obtained pointer invalid.


Just out of curiosity, do you call

x(another_member.getStringMember, fooBar);

?

c_str() returns internal pointer of string object which became invalid as soon as you modify the source string


You are not guaranteed that ptr is still usable after the a="hello" line (since it looks like they are the same string). In your case, since Hello was smaller, and the string wasn't being shared, it looks like it reused the space.

This is implementation specific behavior. It could have easily crashed.


The temp std::string from another_member.getStringElement() goes out of scope after the line is executed. Change

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

to

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


Did you mean to do another_member.getStringElement().c_str() as against another_member.getStringElement.c_str().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜