寻找堆栈损坏错误的解释

Looking for explanation for a stack corruption bug

以下问题是从一个巨大的项目中提炼出来的,也是我能够提出的问题的最小示例。

我知道,从 std::string 派生是不好的,它已经在我们的代码库中进行了更改,但我试图了解这里发生的事情。

代码在 Visual C++ 2017 上崩溃

Microsoft Visual Studio Community 2017 
Version 15.2 (26430.14) Release
Visual C++ 2017   00369-60000-00001-AA257

仅在释放模式下(速度优化)。在没有速度优化的情况下,它不会在发布模式下崩溃。

#include <string>
#include <string_view>
#include <vector>

struct my_string : public std::string
{
    __declspec(noinline)
        my_string::my_string( const std::string_view& str ) :
        std::string( str.data(), str.size() )
    {}

    template <typename T>
    my_string& arg( T )
    {
        return *this;
    }
};

struct my_string_view : public std::string_view
{
    my_string_view( const std::string_view::value_type* val ) :
        std::string_view( val ) {}

    template <typename... PARAMS>
    my_string arg( PARAMS&&... prms ) {
        return my_string( *this ).arg( std::forward<PARAMS>( prms )... );
    }
};

template <typename T>
struct basic_color
{
    T r, g, b, a;

    basic_color() : r( 0 ), g( 0 ), b( 0 ), a( 255 ) {}

    template <typename U>
    explicit basic_color( const basic_color<U>& c ) :
        r( c.r ), g( c.g ), b( c.b ), a( c.a )
    {}
};

using color = basic_color<std::uint8_t>;
using float_color = basic_color<float>;

__declspec(noinline)
void change_float_color( float_color& color )
{
    color.r = 0.1f;
}

int main()
{
    std::vector<float_color> colors = { {} };
    float sum = 0;
    for ( std::uint32_t i = 0; i < 1; ++i )
    {
        float_color fc;
        change_float_color( fc );
        color c( fc );
        std::vector<std::string> msgs;
        msgs.push_back( my_string_view( "" ).arg( c.r ) );
        msgs.push_back( my_string_view( "" ).arg( c.g ) );
        sum += fc.b - colors[i].b;
    }
    return static_cast<int>(sqrt( sum ));
}

Visual Studio的错误是这样的(看下面msgscolors的破损尺寸):

我的猜测是 std::vector<std::string>::push_back(std::string&&)my_string 的调用是有问题的(类似切片的行为)。但是这怎么会破坏堆栈(或堆栈指针)呢?

有没有人知道这里会发生什么或者我怎样才能知道?

Here 是我的项目,以防有人有兴趣重现该问题。

我认为这是一个编译器错误。

这是我从反汇编中看到的:在 main() 条目上,esp 被保存到 ebx 中。最后,espebx 恢复。但是,在中间(调用 std::_Destroy_range1 之后)ebx 值被其他内容覆盖。所以,最后,ret指令使用了一个伪造的esp值,并跳转到了一个无效的地方。

所以,实际上,堆栈没有损坏(这个错误不能像 Hans 所建议的那样用数据断点捕获),但堆栈指针是。