Search code examples
c++objectscopetemporarylifetime

Do temporary objects have scope?


Names have scope (a compile-time property), while objects have lifetimes (a runtime property). Right?

I often see people talking about temporary objects "going out of scope". But since a temporary object does not have a name, I think it does not make sense to talk about "scope" in this context. The lifetime of a temporary object is very clearly defined and has nothing to do with scope. Would you agree?


Solution

  • Names have scope (a compile-time property),

    Yes. I would not call it a property thought. But basically yes.

    while objects have lifetimes (a runtime property). Right?

    There are three types of variables. Each type has different properties in relation to lifetimes.

    • Automatic storage duration:
    • Static storage duration
    • Dynamic storage duration

    Note: automatic storage duration objects have a lifetime that is bound to the scope of the variable.

    I often see people talking about temporary objects "going out of scope".

    Unless bound to a variable a temporary is destroyed at the end of an expression. If they are bound to a variable (a const reference) then they have the same lifespan as the variable. Sometimes it is just easier to refer to this as the scope, but technically you are correct.

    But since a temporary object does not have a name, I think it does not make sense to talk about "scope" in this context.

    Technically yes. But I think it just makes talking about it easier. To me (though not technically correct) the scope of a temporary (not bound) is the expression. Its easier to say than the lifespan of the temporary variable.

    The lifetime of a temporary object is very clearly defined and has nothing to do with scope. Would you agree?

    Yes. But it still feels more natural to talk about scope (even if it is not technically correct). As most people understand what you are trying to imply. But when you get down and talk about the very technical stuff you should use the correct terminology and scope in this context is not correct.