Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Name scope versus object lifetime

Scope determines the context for name lookup in source code, while lifetime describes an object's existence during execution. Hiding a name does not destroy its object. Storage duration is a separate, related concept.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

{ T object{initializer}; /* block scope; automatic storage duration by default */ }

Scope concerns program structure and name lookup, whereas lifetime is a runtime property of an object or reference. A declaration in a nested block can hide a name from an outer block: ordinary use of that name then selects the inner declaration. The outer object still exists.

Generally, an object's lifetime begins when suitably sized and aligned storage has been obtained and initialization, if any, is complete. Special rules exist, including those for unions and implicit object creation. A class object's lifetime ends when its destructor call starts; a non-class object's lifetime ends when it is destroyed. Releasing its storage or reusing it for an object that is not nested within it also ends its lifetime.

Storage duration describes storage availability and can be automatic, static, thread, or dynamic. An ordinary automatic local object is destroyed when its block is exited; such objects are destroyed in reverse construction order. A local static variable has block scope, but its storage lasts for the execution of the program. An object created by new is not automatically destroyed when a local pointer goes out of scope.

In the example, the inner item hides the outer one. Leaving the inner block prints destroy 2, after which the name again denotes the object with value 1. Do not return a pointer or reference to an automatic local object: reading through it after the object's lifetime ends causes undefined behavior. The example uses C++23; the supplied site hosts an evolving draft, not a frozen C++23 text. Execution in a production environment has not been attested.

Examples

#include <iostream>

struct Trace {
    int value;
    ~Trace() { std::cout << "destroy " << value << '\n'; }
};

int main() {
    Trace item{1};
    {
        Trace item{2};
        std::cout << item.value << '\n';
    }
    std::cout << item.value << '\n';
}

Result

2
destroy 2
1
destroy 1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources