返回参考问题 [英] Return a reference problem

查看:116
本文介绍了返回参考问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 我有一个问题(也许这不是一个困难的问题,但是我被困了大约2天),该问题是返回对可变参数模板中的字符串的引用.为了显示我的问题,我将省略可变参数模板部分(问题仍然相同,这对我来说更容易解释).

因此,情况如下:

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:

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:

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
}


那么,我如何设计bridge函数以实现与第一种情况相同的行为?

最好的问候
Filipe Marques


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

Best regards
Filipe Marques

推荐答案

哈哈,非常有趣但很有启发性的bug;感谢您提出这个问题.

要解决该问题,请执行以下操作:replace
Ha-ha, very funny but very instructive bug; thank you for asking this question.

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




with

std::string& bridge(A& a)


我什至必须解释发生了什么事吗?我希望您现在可以自己解决. :-)

—SA


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

—SA


这篇关于返回参考问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆