jeudi 24 décembre 2015

How std::string work in compiler?

Take this question when i read a program (quote:c++ primer plus) 4.22 and make some change in it

#include <iostream>
#include <cstring>

using namespace std;

char * getName();

int main(int argc, const char * argv[]) {
// insert code here...

char *name;

name = getName();
string sb = name;
cout << name << " at " << (int *)name << "\n";
cout << *name << "   " << sb << endl;
cout << &sb << endl;
delete [] name;

name = getName();
sb = name;
cout << name << " at " << (int *) name << "\n";
cout << *name << "   " << sb << endl;
cout << &sb << endl;
delete [] name;

cout << sb << endl;
cout << &sb << endl;

return 0;
}

char *getName()
{
char temp[80];
cout << "Enter last name: ";
cin >> temp;
char *pn = new char[strlen(temp) + 1];
strcpy(pn, temp);
return pn;
}

and there have no memory leak. i check sb's address is different from name. i think may it work like this std::string

first step : malloc (char *, sizeof(char *) * sizeof(name) ) then : snprintf( string , sizeof (string) , "%s", name) final : string get a new address

if i use a statement: string = string + " am i a pointer"; it still work. i guess it is really a pointer! just realloc it

hereby, i think string is kind of char* or char array, i try to *string then the compiler tell me something wrong with it! i can't use like this, so i hope someone can explain what type of string is in compiler and how it work! why string is not a pointer? or it's actually a pointer but it have special method to use? tip:All work on mac os

Aucun commentaire:

Enregistrer un commentaire