I stumbled upon the fact that one can't bind a temporary variable to a reference unless it is a constant and found it to be indeed true in the given code. However, i am not able to find out the difference in my other code snippet where I didn't use const reference but it still work. I couldn't get my head around it.
This is the code where I seek help.
#include <iostream>
#include <sstream>
using namespace std;
void replace(string& str, int length)
{}
int main()
{
try
{
string str="nabh nchy 13 raghav "; //to share the string use std::shared_ptr<std::string> var1 = std::make_shared<std::string>();
replace(str, 19);
cout<<str<<endl;
}
catch(exception& e)
{
cout << "Standard exception: "<<e.what()<<endl;
}
}
Isn't str in the above code temporary. If not, kindly clarify the difference between them.
This is the code where I tried to bind temporary with the reference.
And this is the error which I get if reference on line 16 isn't constant.
gotcha.cpp:24:9: error: invalid initialization of non-const reference of type ‘MyString&’ from an rvalue of type ‘int’
#include <iostream>
#include <string>
using namespace std;
class MyString
{
public:
MyString(int size):str(size, ' ')
{
}
// private:
string str;
};
void print(const MyString& mystr) //error reference needs to be const
{
cout<<mystr.str;
}
int main()
{
int a=3;
print(a);
}