Unique Pointer In C++

SdĂ­let
VloĹžit
  • čas přidĂĄn 29. 08. 2024
  • JOIN ME
    -----
    CZcams 🎬 / @cppnuts
    Patreon 🚀 / cppnuts
    COMPLETE PLAYLIST
    ------------
    C++ Tutorial For Beginners :
    • Introduction To C++
    STL (Standard Template Library) :
    • STL In C++
    ThreadIng In C++ : • Multithreading In C++
    Data Structures: • Data Structure
    Algorithms: • Binary Search
    Design Patterns: • Factory Design Pattern...
    Smart Pointers: • Smart Pointer In C++
    C++14: • Digit Separator In C++
    C++17: • std string_view in C++...
    C++ All Type Casts: • static_cast In C++
    INTERVIEW PLAYLIST
    ------------
    C++ Interview Q&A: • Structural Padding & P...
    C++ Interview Q&A For Experienced: • How delete[] Knows How...
    Linked List Interview Questions: • Find Kth Node From Bac...
    BST Interview Questions: • Search Element In Bina...
    Array Interview Questions: • Reverse An Array
    String Interview Questions: • Check String Is Palind...
    Bit Manipulation Questions: • Find Set Bit In Intege...
    Binary Tree Interview Question: • Invert Binary Tree
    Sorting Algorithms: • Bubble Sort
    C++ MCQ: • Video
    C MCQ: • What printf returns af...
    C Interview Questions: • Designated Initializat...
    QUICK SHORT VIDEOS
    -------------
    C++ Short : • C++ Short Videos
    C Short : • Shorts C Programming MCQ
    In this video we will learn about one of the smart pointer called unique pointer in c++. It is written as unique_ptr.
    NOTES:
    0. unique_ptr is a class template.
    1. unique_ptr is one of the smart pointer provided by c++11 to prevent memory leaks.
    2. unique_ptr wraps a raw pointer in it, and de-allocates the raw pointer,
    when unique_ptr object goes out of scope.
    3. similar to actual pointers we can use arrow and * on the object of unique_ptr, because it is overloaded in unique_ptr class.
    4. When exception comes then also it will de-allocate the memory hence no memory leak.
    5. Not only object we can create array of objects of unique_ptr.
    #stl #cpp #programming #tutorial #interviewquestions #softwareengineering #computerscience

Komentáře • 66

  • @rajanivdeshpande
    @rajanivdeshpande Před 4 lety +4

    Good videos. One clarification, in this ex. the pointer variable "p" will be created on stack so its local in main() ,but the chunk of memory will be allocated on heap. So once we get exception , the pointer "p" goes out of scope hence memory leak because we lost pointer "p" and thus lost the access to chunk of memory on heap.

  • @taihingtse
    @taihingtse Před 4 lety +4

    One of the best explanations!
    This channel just get a new subscriber.

  • @zaspanyflegmatyk2446
    @zaspanyflegmatyk2446 Před 4 lety +4

    Best tutorial on the topic i have ever seen, thank you

  • @ParvezKhanPK
    @ParvezKhanPK Před 4 lety +7

    Dude you are making good videos. Just one suggestion, it is hard to read on mobile screen whatever you have written on the terminal. Better if you can increase the font size or zoom the window.

    • @CppNuts
      @CppNuts  Před 4 lety

      Sure i will try to do something about it. Thanks man..

  • @mohammedsuhailbasha4860
    @mohammedsuhailbasha4860 Před 4 lety +2

    Very nice explaination sir thank you so much sir

  • @treyquattro
    @treyquattro Před 3 lety +1

    good video explaining the idea behind unique_ptr and how to use it (it's like the non-managed C++ version of garbage collection for raw pointers). The only issues I had were that your examples can be a bit hard to follow at first. You know what you intend to show but it's a little confusing, even for a veteran programmer, to follow what you're doing when passing ownership around, releasing pointers, etc. But then that's generally difficult to follow in C++ at the best of times. Maybe more descriptive variable names, including the initial values, e.g. unique_ptr fooptr1_10 = make_unique(10); Then when you e.g. unique_ptr fooptr2_10 = std::move(fooptr1_10) you can see that the contents of fooptr1_10 were moved. Dumping the values of objects after moves to show that the object really was transferred from one place to another might help people unfamiliar with the concept too.

  • @pradeexsu
    @pradeexsu Před 4 lety +1

    Obviously nice video but i like this color combination with white and *cppnuts*
    Rupesh Bhaiya thanks

  • @keshavchandra1996
    @keshavchandra1996 Před 3 lety

    Very nice explanation. Cleared the concept well. Subscribed!

  • @nidhalbouz975
    @nidhalbouz975 Před 3 lety

    Best expalanation of smart pointer i've ever seen

  • @akashaggarwal2853
    @akashaggarwal2853 Před 3 lety

    Nice video but it will be wonderful if you can add some example of storing the array of object in unique pointer.

  • @vijayaraj7610
    @vijayaraj7610 Před 2 lety

    Thanks a lot for nice explanation.. Your videos are really good.. Thank you..

    • @CppNuts
      @CppNuts  Před 2 lety

      Glad you like them!

  • @ganeshjoshi1619
    @ganeshjoshi1619 Před 3 lety

    Thank you so much.
    More power to you ✌, keep going.

  • @shubrochakroborty5918
    @shubrochakroborty5918 Před 9 měsĂ­ci

    Sir how move and release are different?

  • @akmansr7149
    @akmansr7149 Před 2 lety

    I am getting this error on doing this -
    std::unique_ptr t1 = new Test (2000) ;
    error : conversion from 'Test*' to non-scalar type 'std::unique_ptr' requested
    Please help!!!!! Why doesn't = work here?

  • @alexbutane5550
    @alexbutane5550 Před 4 lety +1

    Great video, easy to understand. i still got a problem tough.. i'm trying to allocate a private member vector of unique_ptr to a base class object ( std::vector m_objects ; ) and than to pushback derived classes into it trough a void function that gets nothing and returns nothing but it knows the vector member in the private section of the class because the cpp file belongs to its header file so i use ( m_objects.push_back(std::make_shared (); ) but i always get these linkage errors 2019 and 1120 and i don't know what to do anymore..

  • @vijayaraj7610
    @vijayaraj7610 Před 2 lety

    please do a video with implementing our own unique pointer

  • @jumbo999614
    @jumbo999614 Před 4 lety

    std::unique_ptr p4 = p3.release() doesn't work. So release() is for regular pointer only right?

  • @Recordingization
    @Recordingization Před rokem

    p2.reset(p4),the previous object belonging to p2 is deleted and the p4 becomes a null pointer ,is that correct?

  • @amanagrahari8511
    @amanagrahari8511 Před 4 lety +1

    Sir I want to do specialization in a language. Which language should I prefer for campus placement and for future . Is java better or c++ or other one.

    • @CppNuts
      @CppNuts  Před 4 lety

      Campus placement then java/cpp both are good.
      And after that see what companies gives you after you join. And master that language.

    • @amanagrahari8511
      @amanagrahari8511 Před 4 lety +1

      @@CppNuts thank you so much 🙏🙏 for your suggestion.

  • @swatigupta6881
    @swatigupta6881 Před 2 lety

    If I have a class with unique_ptr as a member, How to write a copy constructor for this class???
    class A
    {
    std::unique_ptr< int > up_;
    public:

    A( const A& a ) {};
    }

  • @181Ravikiran
    @181Ravikiran Před 4 lety

    what all extensions are you using with the Visual studio code editors ? Thanks

  • @arvindganesh7539
    @arvindganesh7539 Před 3 lety

    I thought destructors are called automatically when scope ends. Why is destructor not called in your first run? It has something to do with stack/heap allocation? I'm guessing that when you declare class object with new, only the reference is destroyed at end of scope, not the object. And destructors are called only when the object is destroyed.

    • @saurabhpant
      @saurabhpant Před 2 lety

      First example will be in heap bcs of dynamic allocation bcs of pointer

  • @ikramulmurad
    @ikramulmurad Před 4 lety

    In 9:02, what is the problem if I make single pointer pointed by 2 unique_ptr?

  • @TheJank7
    @TheJank7 Před 3 lety

    Can someone explain me what happens to p4 in line 45 with p2.reset(p4); ? p2 has the ownership of the object of p4 then?

  • @anirudhsharma2384
    @anirudhsharma2384 Před 2 lety

    Is it a memory leak if main exits? I believe no, because if main exits, the entire program exits and memory is freed and given back to OS.

    • @anirudhsharma2384
      @anirudhsharma2384 Před 2 lety

      @sara That's what my point is. In your example 2 your program is not exiting main, while 1 will keep looping indefinitely inside main. My doubt is
      Int main() {
      Int *p = new int(10);
      }
      Is it a memory leak after program exits?
      I believe no! OS takes away memory allocated to your a.out

    • @anirudhsharma2384
      @anirudhsharma2384 Před 2 lety

      @@13taras The point of calling delete everytime is to make most efficient use of memory allocated to the program. If we free memory, the freed memory can then be reused by our program and we do not run out of memory.

  • @D3athW1ng
    @D3athW1ng Před 4 lety

    I'm confused how were you able to set explicit foo (int x): x{x} {} with curly brackets instead of () ?

    • @CppNuts
      @CppNuts  Před 4 lety +1

      This is also one of the way to do it.

    • @treyquattro
      @treyquattro Před 3 lety

      universal initialization using {} is the preferred method. The C++ committee has gone through many attempts to get initialization of all types of object correct, and it still has problems in certain circumstances. Nicolai Josuttis (C++ committee member and prolific book writer and conference presenter) informs us that {} should be used everywhere, even to the extent of doing e.g. for (int i{0}; i < limit; ++i) ... I think most people (including me) will continue to write for (int i = 0; ...) in that instance but everywhere else, for local, member, and global/static variable initialization, {} is a good habit to get into.

  • @surkewrasoul4711
    @surkewrasoul4711 Před 20 dny

    Yea you can, Just use move(ptr)😎

  • @amallaltl1159
    @amallaltl1159 Před 3 lety

    How come a person forgets to call delete. That is so weird.

    • @CppNuts
      @CppNuts  Před 3 lety +1

      Believe me It is good candidate to be forgotten.

  • @sushamasmitesh4929
    @sushamasmitesh4929 Před 4 lety

    What happen if I do delete p after p3.get():
    Foo *p = p3.get();
    delete p;
    what happens with p3? Is it still point to the object in which it was returned?

    • @JayAnAm
      @JayAnAm Před 4 lety

      It still points to the adress in memory, that you deleted. Your program will crash when the p3 gets out of scope and the deleter is called, cause there is nothing left to delete.

    • @aseemsameer7281
      @aseemsameer7281 Před 2 lety

      @@JayAnAm Did you try to execute? It doesn't crash. p is a pointer of type Foo *. It is not a unique pointer, and it holds the address to the object of p3, so p and p3 are 2 different entities. Did you ever see a destructor called for a object pointer being deleted?

  • @nolezquery1100
    @nolezquery1100 Před 3 lety

    can i ask what benefit run code, so importently in linux , as u even using virtual box !

    • @CppNuts
      @CppNuts  Před 3 lety +1

      I like to work in linux, it's just a thing.

  • @GARV_K_JAIN
    @GARV_K_JAIN Před 4 lety

    What is the difference btw move,get, reset and release..

    • @JayAnAm
      @JayAnAm Před 4 lety

      std::move : cast object into rvalue
      get: returns the raw poiner, wrapped by smart pointer
      reset: Replaces the object managed by the smart pointer
      release : Releases the ownership of the managed object

  • @JayAnAm
    @JayAnAm Před 4 lety +1

    Not bad, but you have to be a bit more careful when explaining things like move, espcially when your viewers are not familiar with lvalues and rvalues. std::move doesnt move anything, it is casting into rvalue. And p1 is not a nullpointer after std::move, it is an empty object, just the raw pointer that is wrapped by p1 is nullptr.

    • @CppNuts
      @CppNuts  Před 4 lety

      I don't think its defined that after performing move what remains.
      Actually should be is undefined behavior.

    • @JayAnAm
      @JayAnAm Před 4 lety

      @@CppNuts The state of the p1 after move (which is actually a cast) is unspecified, but it is not nullptr.

    • @CppNuts
      @CppNuts  Před 4 lety

      @@JayAnAm yaa.. Is it like i mentioned it will be nullptr.

    • @JayAnAm
      @JayAnAm Před 4 lety

      @@CppNuts No. Set a breakpoint and see it by yourself in the debugger - the raw pointer is a nullptr, not the unique pointer.

    • @treyquattro
      @treyquattro Před 3 lety

      @@JayAnAm I took Rupesh (?) to mean that the contained raw pointer was set to nullptr after the move, but then I know the subject matter. Making it crystal clear and unambiguous to less experts wouldn't hurt.

  • @181Ravikiran
    @181Ravikiran Před 4 lety

    get deleter video ?

  • @sunandaagt
    @sunandaagt Před 3 lety

    I think you no need to be over conscious of your voice part..... because of this drama, your video content does not come out well. Concentrate on content and good explanation, instead of making singing kind of voice.

    • @CppNuts
      @CppNuts  Před 3 lety

      How many videos did you watched?
      And what is the problem is singing?

  • @akyblr
    @akyblr Před 2 lety

    Many things are wrongly explained(at 5:55) in this video.. So please avoid it.