I'm revisiting C++ after a few years of C#, Javascript, web development etc.
There is a thread where it is explained that the major difference between these is that the at() method does bounds checking and throws an exception if the index provided is out of bounds.
What is the difference between string::at and string::operator[]?
However, that does not seem to justify the following behavior I am experiencing, perhaps someone could help me out?
#include <iostream>
#include <string>
using namespace std;
void remodel(string & str){
string * ps = new string(str);
ps->at(0) = 'n';
cout<<*ps<<endl;
delete ps;
}
int main(){
string str = "Hello world";
remodel(str);
cin.get();
return 0;
}
Output
nello world
In the above code, I use the at() method to change the first character of the string, and am successfully able to do so. Printing the string confirms this.
Something different happens when using the [] operator:
#include <iostream>
#include <string>
using namespace std;
void remodel(string & str){
string * ps = new string(str);
ps[0] = 'n';
cout<<*ps<<endl;
delete ps;
}
int main(){
string str = "Hello world";
remodel(str);
cin.get();
return 0;
}
Output
n
In the above code, using the [] operator on the index 0 replaces the entire string with the letter 'n'. This is confirmed in the debugger where I can see a complete reassignment of values from "Hello world" to "n"
Just to elaborate, if I place a breakpoint so the program stops just before executing ps[0] = 'n', then upon inspecting the variable ps, it seemingly stores an address that is used to reach the string "Hello world". After executing this line, however, the same address can only be used to reach the string/character "n".
My hypothesis was that using the [] operator results in a null character being placed just after specified index..but I have been unable to confirm this.
for example, in the above code using ps[0] I tried to print ps1, ps[2] just to see what would come.
What I got in output either a neverending (empty) output of what seemed like spaces, or a bunch of gibberish. It seems for my null character hypothesis for not to be the case. For good measure, I also tried to manually place a null character at some position like ps[10] but got a segmentation fault..the memory previously allocated to my string had gone out of bounds!
So, it appears I need a good revision on this topic, can someone explain whats going on? Please feel free to let me know if something in this question is vague or badly expressed, I'll do my best to fix it.