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 {
    int *data;
    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;
  • \$\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\$
    – ALX23z
    Apr 17 '20 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\$ Apr 17 '20 at 9:33

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.