Skip to content

focuses on scopedptr class and its lifetimes#16

Open
Butcher3Years wants to merge 1 commit intothis--keywordfrom
Object-Lifetime-(stack-$-scope-lifetimes)
Open

focuses on scopedptr class and its lifetimes#16
Butcher3Years wants to merge 1 commit intothis--keywordfrom
Object-Lifetime-(stack-$-scope-lifetimes)

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Object Lifetimes in C++ – Stack, Heap, and Why Scope Matters

Every object in C++ has a lifetime: the time between when it's created (constructor runs) and when it's destroyed (destructor runs).
Getting lifetimes wrong = one of the biggest sources of bugs: dangling pointers, use-after-free, memory leaks, crashes.

Cherno hammers this home: understand lifetime first, then you can write safe code.

1. Stack / Scoped / Automatic Lifetime – The Safest & Fastest

Objects declared inside a scope (block {}) live on the stack.

void func() {
    int a = 5;                        // lifetime starts here
    Entity e(10, 20);                 // constructor called here

    {                                 // inner scope
        Vector2 v(1.0f, 2.0f);        // lives only inside this {}
    }                                 // v destroyed here (destructor runs)

}                                     // a and e destroyed here (destructors called)

2. Heap / Dynamic Lifetime – You Control It (Danger Zone)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant