在 C++ 中使用 `*this = *obj` 安全吗?

问题描述 投票:0回答:1

我有以下功能:

HttpRequest::HttpRequest(const std::string& request) {
    HttpRequest* req = HttpRequest::parse(request); // Returns dynamically allocated object
    if (req == nullptr) {
        throw HttpException("Invalid request");
    }
    *this = *req;
}

但是

*this = *req
使用安全吗?不会造成内存泄漏吗?

UPD:关于

HttpRequest
有很多问题,所以我决定在这里发布复制方法和析构函数:

HttpRequest& HttpRequest::operator=(const HttpRequest& other) {
    if (this != &other) {
        this->method = other.method;
        this->uri = other.uri;
        // And other fields...
    }
    return *this;
}
~HttpRequest() {
    // Nothing there (There are nothing to delete)
}
static HttpRequest* parse(const std::string& request) {
    // I haven't implemented it yet...
    // I guess it will contain code like this:
    // *Parsing*
    HttpRequest* req = new HttpRequest();
    req.method = "GET"; 
    // *And other fields*
    return req;
}

此外,您可以在pastebin上查看完整代码:

c++
1个回答
0
投票

简短的回答:代码包含内存泄漏。在

delete req
之后添加
*this = *req
。您需要这个,因为
parse
new HttpRequest
(这是有根据的猜测),并且每个
delete
都需要
new

长答案:如果您重新设计代码,您将不需要这些有问题的代码行。请参阅评论以获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.