c++数据成员在单独的成员函数中定义后返回垃圾

C++ data members return garbage after being defined in a separate member function

本文关键字:定义 返回 函数 数据成员 单独 成员 c++      更新时间:2023-10-16

我不知道下面的代码有多少与问题相关,但是我有一个派生类,其中有三个数据成员(loc, remote_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()函数永久改变?

错误在您遗漏的部分。你所拥有的没有什么错,事实上,如果我实现你在评论中所说的,那么我得到预期的输出:

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;
}