Exercise 1-5Is this program valid? If so, what does it do? If not, say why not, and rewrite it to be valid.
#include <iostream>
#include <string>
int main()
{
{ std::string s = "a string";
{ std::string x = s + ", really";
std::cout << s << std::endl; }
std::cout << x << std::endl;
}
return 0;
}
No, the program is not valid.
At the end of the first }, the string x have come to the end of the scope where it is defined and is hence then destroyed. One may then no longer access the string x as it no longer exist.
There are a number of different way to rewrite this program to be valid. Two methods are shown below.
GeSHi (cpp):
#include <iostream>
#include <string>
int main()
{
{ std::string s = "a string";
std::string x = s + ", really";
std::cout << s << std::endl;
std::cout << x << std::endl;
}
return 0;
}Created by GeSHI 1.0.7.18
This one remove the most nested block ({ ... }) making the string x still valid when we get to the output statement.
GeSHi (cpp):
#include <iostream>
#include <string>
int main()
{
{ std::string s = "a string";
std::string x;
{ x = s + ", really";
std::cout << s << std::endl; }
std::cout << x << std::endl;
}
return 0;
}Created by GeSHI 1.0.7.18
This one move the definition of the string x to the outer scope to which the output statement is at. The effect is the same as the first solution above.