Implement std::unique_ptr in C++

preview_player
Показать описание
In this video I have explained how you can implement your own unique_ptr in C++.

________________________________________________________________________________________

Рекомендации по теме
Комментарии
Автор

Dude, why you stopped posting videos.? excellent content and good presentation

ramkan
Автор

These things are completely anonymous to us . Can you recommend a book which includes such content ? Like quant books always have puzzles / maths only .

chiragbansal
Автор

bro great I have a question how unique ptr handles that arrays can you make a video on that ?

ebadjunaid
Автор

do you maintain a repo of all the codes as well?

sunnyyasser
Автор

Thanks for the amazing video. I tried implementing it on my own, can you tell the issues with this implementation (I'm aware it does not handles polymorphism, but can you highlight other issues/potential memory leaks etc?
template<typename T>
class unique_ptr{
T* ptr;
public:
unique_ptr(T* x=nullptr):ptr(x){}
//we don't want to allow copy!
//delete copy constuctor and copy assignment!
unique_ptr(const unique_ptr& x) = delete;
unique_ptr& operator=(const unique_ptr& x) = delete;
//we need to make a move constructor and move assignment!
unique_ptr(unique_ptr&& x){
std::cout<<"move constructor called \n";
ptr = x.ptr;
x.ptr = nullptr;
}
unique_ptr& operator=(unique_ptr&& x){
std::cout<<"move assignment called \n";
if (ptr!=x.ptr){
delete ptr;
ptr=x.ptr;
x.ptr=nullptr;
return *this;
}else{
return *this;
}
}
T& operator*(){
return *ptr;
}
T* operator->(){
return ptr;
}
~unique_ptr(){
delete ptr;
}
};

praveensingh
Автор

Really bad practice to create a raw pointer and then assign it to a smart pointer. In this case "i" is no more the owner of the memory but someone can use it. If some exception raises before assignment the memory pointed by "i" will be no more deallocated. This way is also anti semantic, you talk about an exlusive owner but use a raw pointer as an intermediary, It's no sense.
It's better to create the object using directly the constructor of unique_ptr:
std::unique_ptr<int> uptr = std::make_unique<int>(5);
If you still want to use or need to use a raw pointer It's better to move the property via std::move
int* i = new int {5};
std::unique_ptr<int> uptr{std::move(i)}:

dillon