Reputation: 50667
From Strings in Depth, I learn that the exact implementation of memory layout for the string class is not defined by the C++ Standard. But how come &string
and &string[0]
will have different memory addresses?
string variable("String Test");
cout << (void *) &variable << endl; // 003EFE58
cout << (void *) &variable[0] << endl; // 003EFE5C
cout << (void *) &variable[1] << endl; // 003EFE5D
... ...
But they do share the same content, check out:
cout << ((string)*(&variable))[0] << endl; // 'S'
cout << *(&variable[0]) << endl; // 'S'
Can anyone explain what's going on here?
Upvotes: 1
Views: 980
Reputation: 1816
This happens to confuse a lot of programmers, so I will do my best to explain it.
// here, you take the address (&) of the first item in the variable array...
// you then convert that address to a string object
// an implicit cast occure, which constructs a string instance and copies the contents of
// the referenced item in variable (which is a dereferenced char* char('S'))
// this line is similar to:
// char c = *(&variable[0]); // dereference
// string S = string(c); // copy
// printf("%c\n", S); // print
printf("%c\n", ((string)*(&variable))[0]); // 'S'
// here, you do the same dereference of the first item in variable,
// except you don't copy it into a string object
// similar to
// char c = *(&variable[0]);
// printf("%c\n", c);
printf("%c\n", *(&variable[0])); // 'S'
Upvotes: 0
Reputation: 10557
String is an object. It has some fields in its beginning. This is implementation specific. In your case there is just one 4 bytes field. The sting that it contains starts with an offset. In fact, the sting can be in a heap buffer. It may not be in the object itself.
Upvotes: 2
Reputation: 272477
Because one is the address of the class instance, the other is the address of the first character, which is typically contained in dynamically-allocated memory managed by the class (or somewhere in the instance itself in the case of SSO).
Upvotes: 6