/*std::unique_ptr is a smart pointer provided by the C++ Standard Library. It is a template class that is used for managing single
objects or arrays.
unique_ptr works on the concept of exclusive ownership - meaning only one unique_ptr is allowed to own an object at a time.
This ownership can be transferred or moved, but it cannot be shared or copied.
This concept helps to prevent issues like dangling pointers, reduce memory leaks, and eliminates the need for manual memory management.
When the unique_ptr goes out of scope, it automatically deletes the object it owns.
*/
//IMP
/*
Yes, you're correct. A std::unique_ptr is designed for exclusive ownership, meaning it cannot be copied, only moved.
Once a std::unique_ptr goes out of scope (for example, when the function in which it's declared ends),
the memory it manages is automatically released.
*/
#include <iostream>
#include <memory>
//note all functions in c++ should be written in class
class fun{
public:
int check(){
std::unique_ptr<int> ptr (std::make_unique<int>(3));
std::cout<<"inside fun valid"<<std::endl;
return *ptr;
}
};
int main(){
int *ptr (new int(1));
std::unique_ptr<int> ptr2 (std::make_unique<int>(2));
std::cout<<*ptr<<*ptr2<<std::endl;
delete ptr;
//This ownership can be transferred or moved, but it cannot be shared or copied.
std::unique_ptr<int> ptr3 (std::move(ptr2));
std::cout<<*ptr3<<std::endl;
// but it cannot be shared or copied
fun f1;
int a = f1.check();
std::cout<<a<<std::endl;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: