mercredi 16 novembre 2022

unique_ptr is copying when raw pointer is passed into its constructor

I am trying to understand how unique pointers work in modern C++.

When I went through the documentations (cppreference and others), I was able to understand that unique_ptr will transfer ownership and not share it. But I am not able to understand why unique_ptr is acting strange when working with a raw pointer passed into its constructor.

For example:

#include <iostream>
#include <memory>

class foo{
    int x;
public:
    foo(): x(0) {}
    foo(int a): x(a) {}
    foo(const foo& f): x(f.x) {}
};

int main(){
    foo *ptr = new foo(5);
    std::unique_ptr<foo> uptr(ptr);
    std::cout << ptr << "\n";
    std::cout << uptr.get() << "\n";
    return 0;
}

Output below:

0x5c7bc80
0x5c7bc80

Queries:

  • Is the raw pointer being passed into the copy constructor? Isn't the copy constructor deleted (=delete)? Why is the raw pointer printing the same address as unique_ptr?
  • Is this a design flaw of unique_ptr?
  • How do I overcome this issue?
  • What is the use of std::make_unique()? I tried change the line std::unique_ptr<foo> uptr(ptr); to std::unique_ptr<foo> uptr(std::make_unique<foo>(*ptr)); but nothing changed.

Aucun commentaire:

Enregistrer un commentaire