Why do c++ inbuilt string functions return a reference to an object?
I was looking in place the c++ normal library and ran into the String class as well as noticed that the assignment owner returns a reference to help an object.Ex:
string& operator= ( const string& str );
Why can we ought to use “string&” Why return any reference
One more question, we pass while in the string for a reference (i.at the., the string& str) aspect.Why possibly not pass inside string as a pointer
1)
That’s the conventional behavior connected with operator= with any C++ class, not just the string class.You’d often be making a strong unnecessary copy if you ever returned simply by value.
2)
Why could you pass the item in for a pointer That might be weird syntax.
string a, b = “Hello”;
some sort of = &b;
Rather then the a lot more sensible:
string a, b = “Hello”;
some sort of = b;
Among the list of core ideas of C++ is user described classes could behave with almost the exact same manner while built-in forms like int, char, float etc…Your string training, as good as the vast majority of rest with the classes inside standard catalogue, try to live up to that suitable.
Special Because of WaMSie.
/question/accuse_write; _ylt=A0WTZVrgNNBNmlsAKgty7hR.; _ylv=3qid=20110509120343AAJAtKq&kid=RsZ8Wjq5VTSvDi4aMWLqWryrXx0w38NPfLVJYf2ciUDFCNtATbEh&s=comm&date=2011-05-11+04%3A23%3A51&.crumb=CklVYK7bKa1″ class=”report-abuse
References will be really syntactic suscrose for ideas.The just semantic variance between any pointer along with a reference is that you should explicitly initialise the reference, whereas your pointer doesn’t has to be initialised.
So “string& operator=(const string& str)” is essentially like “string* (const string* str)” and would make to the exact same code.
With the reference form you’ll be able to write:
string a = “hello”;
string b;
b = some sort of;
Using the actual pointer form you possibly can write the same thing:
string a = “hello”;
string b;
b = &c;
But in which extra & type of spoils this flow.
Moreover there is a normal premiss that sources are non-null when pointers can be.
int* p = 0; // Easy to produce a null tip.
int& ur = *static_cast(0); // Harder and sillier to produce a null research.
To solution both ones questions, it’s making sure that code such as ‘a=b=”hello”; ‘ are appropriate just for instance ‘i=j=0; I works.
Leave a Reply
You must be logged in to post a comment.