0
\$\begingroup\$

I decided to implement a simple smart pointer class in C++ name my_pointer. Please review this code.

#include <iostream>
using namespace std;
class my_pointer {
private:
 int *data;
public:
 explicit my_pointer(int *p = nullptr) : data(p) {}
 int& operator *() {
 return *data;
 }
 ~my_pointer() {
 delete data;
 data = nullptr;
 }
};
int main() {
 int *p = new int;
 *p = 50;
 my_pointer pointer(p);
 cout << *pointer;
 return 0;
}
asked Apr 17, 2020 at 4:07
\$\endgroup\$
2
  • \$\begingroup\$ Yeah, this really bad and there is nothing to review. Read at least the most basic guides on C++ prior to making a post. \$\endgroup\$ Commented Apr 17, 2020 at 9:13
  • \$\begingroup\$ I think this post might be a good starting point to read up on the rule of three. Also, try to consider edge cases (e.g. what happens if you instantiate my_pointer without argument and it goes out of scope)? I'm also new to codeReview, but I think if you solve these issues and test your code more extensively (Try using the assignment operator on your instances etc.) more people would consider this post to be on-topic for a codeReview. \$\endgroup\$ Commented Apr 17, 2020 at 9:33

1 Answer 1

2
\$\begingroup\$

What is the purpose of this simple smart pointer class? It seems meaningless and hiding terrible mistakes. The use of it could be very dangerous. Simple example:

void f()
{
 my_pointer p1{ new int }
 //some code
 my_pointer p2 = p1;
 //some code
}

If we call f() the result will be terrible. The memory allocated for int is freed twice.

There is no need to assign data nullptr because the object is not meant to be used after call of destructor.

answered Apr 23, 2020 at 13:20
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.