Skip to content

Commit 797a5d5

Browse files
committed
fix: avoid using C-style pointers to prevent potential memory leaks
Signed-off-by: syaojun <[email protected]>
1 parent 080a2f6 commit 797a5d5

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

cpp/src/graphar/status.h

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
#pragma once
2121

22+
#include <memory>
2223
#include <sstream>
2324
#include <string>
2425
#include <type_traits>
@@ -131,33 +132,38 @@ class Status {
131132
/** Create a success status. */
132133
Status() noexcept : state_(nullptr) {}
133134
/** Destructor. */
134-
~Status() noexcept {
135-
if (state_ != nullptr) {
136-
deleteState();
137-
}
138-
}
135+
~Status() noexcept = default;
139136
/**
140137
* @brief Constructs a status with the specified error code and message.
141138
* @param code The error code of the status.
142139
* @param msg The error message of the status.
143140
*/
144141
Status(StatusCode code, std::string msg) {
145-
state_ = new State;
142+
state_ = std::make_unique<State>();
146143
state_->code = code;
147144
state_->msg = std::move(msg);
148145
}
149146
/** Copy the specified status. */
150-
Status(const Status& s)
151-
: state_((s.state_ == nullptr) ? nullptr : new State(*s.state_)) {}
152-
/** Move the specified status. */
153-
Status(Status&& s) noexcept : state_(s.state_) { s.state_ = nullptr; }
154-
/** Move assignment operator. */
155-
Status& operator=(Status&& s) noexcept {
156-
delete state_;
157-
state_ = s.state_;
158-
s.state_ = nullptr;
147+
Status(const Status& s) {
148+
if (s.state_) {
149+
state_ = std::make_unique<State>(*s.state_);
150+
}
151+
}
152+
/** Copy assignment operator. */
153+
Status& operator=(const Status& s) {
154+
if (this != &s) {
155+
if (s.state_) {
156+
state_ = std::make_unique<State>(*s.state_);
157+
} else {
158+
state_.reset();
159+
}
160+
}
159161
return *this;
160162
}
163+
/** Move the specified status. */
164+
Status(Status&& s) noexcept = default;
165+
/** Move assignment operator. */
166+
Status& operator=(Status&& s) noexcept = default;
161167

162168
/** Returns a success status. */
163169
static Status OK() { return {}; }
@@ -262,16 +268,11 @@ class Status {
262268
}
263269

264270
private:
265-
void deleteState() {
266-
delete state_;
267-
state_ = nullptr;
268-
}
269-
270271
struct State {
271272
StatusCode code;
272273
std::string msg;
273274
};
274-
State* state_;
275+
std::unique_ptr<State> state_;
275276
};
276277

277278
} // namespace graphar

0 commit comments

Comments
 (0)