Feedback on my C++ program #144943
Replies: 2 comments 5 replies
-
Yes. This |
Beta Was this translation helpful? Give feedback.
-
Hi @DumbestPerson224, Issues and Suggestions:
Improved Version:If you'd like to keep practicing and refining your implementation, here's an improved version based on your current approach: #include <iostream>
template <typename T>
class auto_ptr {
private:
T* pointer = nullptr;
public:
bool auto_manage = true;
// Default constructor
auto_ptr() {
if (auto_manage) {
pointer = new T();
}
}
// Constructor accepting a raw pointer
explicit auto_ptr(T* ptr) : pointer(ptr) {}
// Destructor
~auto_ptr() {
if (auto_manage && pointer) {
delete pointer;
}
}
// Prevent copy semantics
auto_ptr(const auto_ptr&) = delete;
auto_ptr& operator=(const auto_ptr&) = delete;
// Enable move semantics
auto_ptr(auto_ptr&& other) noexcept : pointer(other.pointer), auto_manage(other.auto_manage) {
other.pointer = nullptr;
}
auto_ptr& operator=(auto_ptr&& other) noexcept {
if (this != &other) {
if (auto_manage && pointer) {
delete pointer;
}
pointer = other.pointer;
auto_manage = other.auto_manage;
other.pointer = nullptr;
}
return *this;
}
// Access the managed object
T* operator->() const {
return pointer;
}
T& operator*() const {
return *pointer;
}
}; Explanation of Changes:
Keep up the good work and happy coding! 😊 |
Beta Was this translation helpful? Give feedback.
-
Body
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions