Implement customer unique pointer

I am writing unique pointer implementation for Arduino platform.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
template<typename T>
class Pointer {
    T *t;


public:
    Pointer(T *t) : t(t) {}

    virtual ~Pointer() {
        delete t;
        t = new int{10};
    }

    T *getT() const {
        return t;
    }
};


Pointer<int> getPointer() {
    return {new int{7}};
};

std::unique_ptr<int> getUniquePointer() {
    return std::unique_ptr<int>{new int{8}};
}


int main() {

    int *number1 = getUniquePointer().get();
    std::cout << *number1 << std::endl;

    int *number2 = getPointer().getT();  
    std::cout << *number2 << std::endl;

    return 0;

}


The problem I have is getPointer call in int *number2 = getPointer().getT(); is an rvalue, so when statement is done the destructor of Pointer is invoked and the memory is corrupted. I checked the same behavior for c++ unique_ptr and it looks like different - the expected number is printed. Is it actually different or unique pointer was deleted and I just refer to old memory?

If it is different how can I disable rvalue for my object - I mean I don't want Pointer object ever be in rvalue(temporary variable).
Last edited on
Both number1 and number2 have the same problem. They are dangling pointers.

The correct way would be to store it as a unique_ptr.

1
2
std::unique_ptr<int> number1 = getUniquePointer(); 
std::cout << *number1 << std::endl;


Note that a unique_ptr can't be copied. It can only be moved. The move constructor, and the move assignment operator, transfers the pointer value from the right hand side to left hand side.

1
2
3
auto up1 = std::make_unique<int>(8);
auto up2 = std::move(up1); // move constructor transfers the pointer so that 
                           // up2 points to int 8, while up1 becomes nullptr 
Last edited on
Topic archived. No new replies allowed.