【问题标题】:C++ data members return garbage after being defined in a separate member functionC++ 数据成员在单独的成员函数中定义后返回垃圾
【发布时间】:2014-06-05 22:36:44
【问题描述】:

我不知道下面的代码有多少与问题相关,但我有一个包含三个数据成员(locremote_hostremote_port)的派生类。它们在类的头文件中声明,并在Initialize() 成员函数中定义。但是,当HandleRequest() 函数尝试访问它们时,remote_hostremote_port 分别返回垃圾和 0; loc 按预期返回 "/proxy"。有人可以指出明显的吗?我迷路了……

// in response_handler.hh
class ResponseHandlerInterface {
  public:
    virtual bool Initialize(const NginxConfig& config) = 0;
    virtual bool HandleRequest(const std::string& request, std::string* response) = 0;
};


// in ProxyHandler.hh
class ProxyHandler : public ResponseHandlerInterface {
  public:
    std::string loc, remote_host;
    int remote_port;
    bool Initialize(const NginxConfig&);
    bool HandleRequest(const std::string&, std::string*);
};


// in ProxyHandler.cc
bool ProxyHandler::Initialize(const NginxConfig &config) {
  loc = "/proxy";
  remote_host = "digboston.com";
  remote_port = 80;
  std::cout << "Values in Initialize():" << std::endl;
  std::cout << loc << " " << remote_host << " " << remote_port << std::endl;
  return true;
}

bool ProxyHandler::HandleRequest(const std::string &request, std::string *response) {
  std::cout << "Values in HandleResponse():" << std::endl;
  std::cout << loc << " " << remote_host << " " << remote_port << std::endl;
  return true;
}


// in main.cc
  // a new instance of ProxyHandler is created,
  // Initialize() is called on the object,
  // HandleRequest() is called on the object.

这是输出:(

>> ./runprogram

Values in Initialize():
/proxy digboston.com 80

Values in HandleResponse():
/proxy H?/P??P??    P??@    P??`    P?? 0

如您所见,loc 保留了它的价值。 remote_hostremote_port 保存它们初始化时的垃圾值。我该怎么做才能确保所有三个值都从 Initialize() 函数中永久更改??

【问题讨论】:

  • 在 C++ 中,它们被称为成员函数,而不是方法。
  • 最好不要贴sn-ps,而是构造一个testcase,这样我们可以自己重现问题,玩一玩。这实际上是调试的关键部分,所以在发布之前这样做。 sscce.org 老实说,我希望有人在 SO 上工作了两年并发布了 40 多个问题,现在知道这一点。
  • 如果真的按照您的建议,说明的顺序没有任何问题。您是否省略了其他相关代码?你最后一次清理和重建是什么时候?你能告诉我们对象是如何实例化和访问的吗?
  • 对象是如何被实例化然后被使用的?我在黑暗中的镜头是您实例化的变量与您正在打印的变量不同。尝试在两个打印输出中打印出this 指针,以确保它是同一个对象。
  • @LightnessRacesinOrbit 谢谢你的链接,我会读一读。我同意你的看法……我想我们最终都会学到这一课,现在是我的时候了。对不起那些家伙。

标签: c++ class member


【解决方案1】:

错误在您遗漏的部分。你所拥有的没有任何问题,事实上,如果我在你的 cmets 中实现你所说的,那么我会得到预期的输出:

Values in Initialize():
/proxy digboston.com 80
Values in HandleResponse():
/proxy digboston.com 80

我的补充如下:

#include <iostream>

struct NginxConfig {};

// YOUR CODE GOES HERE

int main() {
  ProxyHandler ph;
  ph.Initialize(NginxConfig());
  ph.HandleRequest(std::string(""), NULL);
  return 0;
}

【讨论】:

  • 确实,我也得到了同样正确的输出。可能 OP 忘记了 Initialize() 对象,或者正在以某种方式删除它。
  • @vsoftco 可能是这样。我在其他人的代码库中工作,他们正在使用new 创建一个对象,但这可能是一个范围问题。 (虽然,loc 很好)。
  • @vsoftco 即使你忘记了Initialize,这些都是std::string 对象;他们有构造函数。无论如何,示例输出显示来自Initialize 的跟踪。
  • @Kaz,是的,可能访问是通过无效指针完成的,但我们只能从发布的代码中猜测。
  • 所以,总而言之,你没有回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多