Безопасно ли использовать `*this = *obj` в C++? ⇐ C++

Программы на C++. Форум разработчиков
Anonymous
Безопасно ли использовать `*this = *obj` в C++?

Сообщение Anonymous »

У меня есть следующая функция:

Код: Выделить всё

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:

Подробнее здесь: https://stackoverflow.com/questions/791 ... o-use-in-c

Вернуться в «C++»