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

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

    Because the standards committee goofed. It does it because they chose to make it do it. It's defined to do it this way. It should be considered an anonymous instance with scope the same as if it had been named. From the point of instantiation to the end of the block. Apparently they thought the only use was for passing temporaries into functions where it's pushed on the stack and popped off the stack at the end of a function call...

    An unnamed object should still be pushed onto the stack and remain on the stack until the block ends, thus popping it off the stack when expected. Constructing and destructing an object during a single statement is pointless. I'd like to see a single instance/case where this is actually useful. If it doesn't stay in scope for the duration of the block it should most certainly be an error and should at minimum generate a warning.

提交回复
热议问题