crashed during printing string reference.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<string>
 const  std::string&  test()
{
	return "sandeep poudel";
}

int main()
{
	
	std::cout << test() << std::endl; //couldn't do this.
	std::cin.get();
}

in above code how can i print the returned string. i must return by the reference. can't i do that? program ended with unwxceptional handling and was not able to print sandeep poudel.
The function constructs a temporary std::string object and returns a reference to it. The problem is that as soon as the function ends the temporary object gets destroyed so when it is time to print the string it no longer exists.

Either return a const char* or return the std::string by value.
Last edited on
You cannot return a reference to local values. Let the compiler deal with optimizations.

1
2
3
4
std::string test()
{
  return "Sandeep Poudel";
}

sandeeppoudel wrote:
i must return by the reference

Did you actually mean this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<string>
void test( std::string &s )
{
	s = "sandeep poudel";
}

int main()
{
	std::string s;
	test( s );
	std::cout << s << '\n';
//	std::cin.get();
}
Last edited on
1
2
3
4
5
std::string const& test()
{
  static std::string name{ "Sandeep Poudel" };
  return name;
}


Topic archived. No new replies allowed.