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

前端 未结 5 1111
佛祖请我去吃肉
佛祖请我去吃肉 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:23

    Yes, it is desired.

    Foo foo("three") creates a normal object which will be destroyed when the scope ends.

    Foo("one") creates a temporary object, which is destroyed at the end of the instruction[1]. Why? Because there is no way you can access it after the instruction has ended.

    [1] Deliberate simplification: I should have said sequence point.

提交回复
热议问题