Why do un-named C++ objects destruct before the scope block ends?

前端 未结 5 1103
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 06:52

The following code prints one,two,three. Is that desired and true for all C++ compilers?


class Foo
{
      const char* m_name;
public:
      Foo(const char         


        
5条回答
  •  时光取名叫无心
    2020-11-29 07:09

    The rules that govern the lifetimes of temporary objects have nothing to do with notion of scope. Scope is a property of a name, and temporary objects do not have names. In other words, temporary objects have no scope.

    Most of the time the lifetime of a temporary object ends at the end of the full expression that created that object, which is what you observed in your experiment. This is the general rule that has some exceptions. The main one is that if you immediately attach a reference to your temporary object, the lifetime of the object will be extended to match the lifetime of the reference

    const Foo &rfoo = Foo("one");
    

    The above temporary will live as long as rfoo lives.

提交回复
热议问题