Click here to Skip to main content
15,905,915 members
Please Sign up or sign in to vote.
4.11/5 (2 votes)
See more:
Hi I have a problem (maybe it is not a difficult problem but I am stuck for about 2 days) that is to return a reference to a string in a variadic template. To show my problem, I will omit the variadic template part (the problem still the same and it is for me easier to explain).

So, the situation is the follows:

C++
class A
{
public:
  A() {}
  ~A(){}
  std::string str;

  std::string& get_str() {return str;};
};

void wmain( int argc, char** args)
{
  A a;
  a.get_str() = "hello world";
  // now a.str value is 'hello world', works as expected
}
Now I will add a function in the middle of the process:

C++
class A
{
public:
  A() {}
  ~A(){}
  std::string str;

  std::string& get_str() {return str;};
};

std::string& bridge(A a)
{
  return a.get_str();
}

void wmain( int argc, char** args)
{
  A a;
  bridge(a) = "hello world"; // a little error :D
}

So, how I must design the bridge function to achieve the same behavior as in the first case?

Best regards
Filipe Marques
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jan-15 19:07pm    
Up-voted the question. This is a fairly elementary bug, but such examples are very good to illustrate some basic notions; they are pretty hard to invent. In some ways, C++ references
are relatively hard to understand. Also, this example illustrates the dangers of C++ conceptions and teaches us to be more careful.
Thank you for asking, please see my answer.
—SA

1 solution

Ha-ha, very funny but very instructive bug; thank you for asking this question.

To sort it out, do the following: replace
C++
std::string& bridge(A a)

with
C++
std::string& bridge(A& a)

Do I even have to explain what's going on? I hope now you can figure it out by yourself. :-)

—SA
 
Share this answer
 
v4
Comments
Filipe Marques 8-Jan-15 3:59am    
Hahaha I knew it that was a very difficult error :D Yes, I understand why. I have always been concerned about return a reference but never pay attention to the function arguments. Thanks a lot Sergey :) Best regards, Filipe Marques
Sergey Alexandrovich Kryukov 8-Jan-15 11:21am    
Great. You are very welcome.
This function argument by value causes another instance of the class to be copy-constructed and destroyed.
Good luck, call again.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900