Why does using a temporary object in the range-based for initializer result in a crash?

后端 未结 2 1080
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 02:33

Why does the following code crash both on Visual Studio and GCC?

For it to crash it requires the range-based for loop, std::map, std::string and taking a reference t

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 03:15

    S().func()
    

    This constructs a temporary object, and invokes a method that returns a reference to a std::string that's owned (indirectly) by the temporary object (the std::string is in the container that's a part of the temporary object).

    After obtaining the reference, the temporary object gets destroyed. This also destroys the std::string that was owned (indirectly) by the temporary object.

    After that point, any further usage of the referenced object becomes undefined behavior. Such as iterating over its contents.

    This is a very common pitfall, when it comes to using range iteration. Yours truly is also guilty of getting tripped over this.

提交回复
热议问题