Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
const reference life time extension
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <sstream> using namespace std; using std::cout; using std::endl; class CSomeClass { protected: string m_Text; public: CSomeClass(const string& NewText) { m_Text = NewText; } void ChangeText(const string& NewText) { m_Text = NewText; } //Getters string GetTextCopy() const { return m_Text; } string& GetTextRef() { return m_Text; } const string& GetTextRef() const { return m_Text; } }; int main() { CSomeClass SomeClass("OriginalText"); string TextCopy = SomeClass.GetTextCopy(); //Ok, copying text cout << string("TextCopy: ") << TextCopy << endl; const string& ConstTextRef = SomeClass.GetTextRef(); //Ok, taking reference to original string inside SomeClass cout << "ConstTextRef: " << ConstTextRef << endl; const string& RefToCopy = SomeClass.GetTextCopy(); //Ok, taking cosnt reference to copy of string cout << "RefToCopy: " << RefToCopy << endl; SomeClass.ChangeText("ModifiedText"); cout << "RefToCopy after modifying original string: " << RefToCopy << endl; //Still references old copy of string. That one has not been modified cout << "ConstTextRef after modifying original string: " << ConstTextRef << endl; //Still references the string that has now been changed const string& ConstTextRefAfterModification = SomeClass.GetTextCopy(); //Will now reference a new copy of the updated string cout << "ConstTextRefAfterModification: " << ConstTextRefAfterModification << endl; //What is then not allowed? string& NonConstRefToTemp = SomeClass.GetTextCopy(); cout << "NonConstRefToTemp: " << NonConstRefToTemp << endl; //On VC++, this works just fine but gives a level 4 warning. Other compilers give a compile error as the standard dictates. return 0; }
run
|
edit
|
history
|
help
0
hangman
Computing factorial of an integer with recursion and iteration
Matrix paths right-down only, going through XY
throwing Copyable versus throwing MoveOnly
trying to find if reinterpret_cast preserves calling convention
C++ instantiation
Matrix_1
error_check
Policy class partial specialization inheritance
Static cast of Enum