Stack, Static, and Heap in C++

前端 未结 9 1995
温柔的废话
温柔的废话 2020-11-22 05:17

I\'ve searched, but I\'ve not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what\'s its real advantage? What are the

相关标签:
9条回答
  • 2020-11-22 05:46

    An advantage of GC in some situations is an annoyance in others; reliance on GC encourages not thinking much about it. In theory, waits until 'idle' period or until it absolutely must, when it will steal bandwidth and cause response latency in your app.

    But you don't have to 'not think about it.' Just as with everything else in multithreaded apps, when you can yield, you can yield. So for example, in .Net, it is possible to request a GC; by doing this, instead of less frequent longer running GC, you can have more frequent shorter running GC, and spread out the latency associated with this overhead.

    But this defeats the primary attraction of GC which appears to be "encouraged to not have to think much about it because it is auto-mat-ic."

    If you were first exposed to programming before GC became prevalent and were comfortable with malloc/free and new/delete, then it might even be the case that you find GC a little annoying and/or are distrustful(as one might be distrustful of 'optimization,' which has had a checkered history.) Many apps tolerate random latency. But for apps that don't, where random latency is less acceptable, a common reaction is to eschew GC environments and move in the direction of purely unmanaged code (or god forbid, a long dying art, assembly language.)

    I had a summer student here a while back, an intern, smart kid, who was weaned on GC; he was so adament about the superiorty of GC that even when programming in unmanaged C/C++ he refused to follow the malloc/free new/delete model because, quote, "you shouldn't have to do this in a modern programming language." And you know? For tiny, short running apps, you can indeed get away with that, but not for long running performant apps.

    0 讨论(0)
  • 2020-11-22 05:49

    The following is of course all not quite precise. Take it with a grain of salt when you read it :)

    Well, the three things you refer to are automatic, static and dynamic storage duration, which has something to do with how long objects live and when they begin life.


    Automatic storage duration

    You use automatic storage duration for short lived and small data, that is needed only locally within some block:

    if(some condition) {
        int a[3]; // array a has automatic storage duration
        fill_it(a);
        print_it(a);
    }
    

    The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.


    Static storage duration

    You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have namespace scope and local scope and class scope. What is true about both of them is, once their life begins, lifetime ends at the end of the program. Here are two examples:

    // static storage duration. in global namespace scope
    string globalA; 
    int main() {
        foo();
        foo();
    }
    
    void foo() {
        // static storage duration. in local scope
        static string localA;
        localA += "ab"
        cout << localA;
    }
    

    The program prints ababab, because localA is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime when control reaches their definition. For localA, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at program startup. The same is true for static objects of class scope:

    class A {
        static string classScopeA;
    };
    
    string A::classScopeA;
    
    A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;
    

    As you see, classScopeA is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term static initialization order fiasco.


    Dynamic storage duration

    The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are big, and if you want to create arrays of size only known at runtime. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate new operator invocation happens:

    int main() {
        // the object that s points to has dynamic storage 
        // duration
        string *s = new string;
        // pass a pointer pointing to the object around. 
        // the object itself isn't touched
        foo(s);
        delete s;
    }
    
    void foo(string *s) {
        cout << s->size();
    }
    

    Its lifetime ends only when you call delete for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. Explicit garbage collection for particular objects can be established by using a smart pointer:

    int main() {
        shared_ptr<string> s(new string);
        foo(s);
    }
    
    void foo(shared_ptr<string> s) {
        cout << s->size();
    }
    

    You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So its lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared_ptr reference, see boost documents: http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm

    0 讨论(0)
  • 2020-11-22 05:49

    Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.

    You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.

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