C++ dynamically allocated memory

前端 未结 8 1852
难免孤独
难免孤独 2020-12-10 16:16

I don\'t quite get the point of dynamically allocated memory and I am hoping you guys can make things clearer for me.

First of all, every time we allocate memory we

相关标签:
8条回答
  • 2020-12-10 16:58
    1. Your program gets an initial chunk of memory at startup. This memory is called the stack. The amount is usually around 2MB these days.

    2. Your program can ask the OS for additional memory. This is called dynamic memory allocation. This allocates memory on the free store (C++ terminology) or the heap (C terminology). You can ask for as much memory as the system is willing to give (multiple gigabytes).

    The syntax for allocating a variable on the stack looks like this:

    {
        int a; // allocate on the stack
    } // automatic cleanup on scope exit
    

    The syntax for allocating a variable using memory from the free store looks like this:

    int * a = new int; // ask OS memory for storing an int
    delete a; // user is responsible for deleting the object
    


    To answer your questions:

    When is one method preferred to the other.

    1. Generally stack allocation is preferred.
    2. Dynamic allocation required when you need to store a polymorphic object using its base type.
    3. Always use smart pointer to automate deletion:
      • C++03: boost::scoped_ptr, boost::shared_ptr or std::auto_ptr.
      • C++11: std::unique_ptr or std::shared_ptr.

    For example:

    // stack allocation (safe)
    Circle c; 
    
    // heap allocation (unsafe)
    Shape * shape = new Circle;
    delete shape;
    
    // heap allocation with smart pointers (safe)
    std::unique_ptr<Shape> shape(new Circle);
    

    Further more why do I need to free up memory in the first case, but not in the second case.

    As I mentioned above stack allocated variables are automatically deallocated on scope exit. Note that you are not allowed to delete stack memory. Doing so would inevitably crash your application.

    0 讨论(0)
  • 2020-12-10 17:01

    What happens if your program is supposed to let the user store any number of integers? Then you'll need to decide during run-time, based on the user's input, how many ints to allocate, so this must be done dynamically.

    0 讨论(0)
提交回复
热议问题