c++ - Access violation on ending the main function scope but only with Visual Studio 2019 and gcc - Stack Overflow

时间: 2025-01-06 admin 业界

I don't understand why I'm getting the access violation on reading location on leaving the main function scope in this program:

#include <iostream>
#include <string>

struct SimpleStructBase
{
    int* intPointer;
};

struct MemHolder
{
    SimpleStructBase& params;
    MemHolder(SimpleStructBase& dist) : params(dist)
    {
        params.intPointer = new int(*dist.intPointer);
    }

    ~MemHolder()
    {
        delete params.intPointer;
    }
};

struct SimpleStructMng : SimpleStructBase
{
protected:
    SimpleStructMng(SimpleStructBase& params) : SimpleStructBase(params) {}
    std::shared_ptr<MemHolder> mem;

public:
    ~SimpleStructMng() {}

    static SimpleStructMng CreateStruct(SimpleStructBase& params)
    {
        SimpleStructMng ret = { params };
        ret.mem = std::make_shared<MemHolder>(ret); //This thing crashes
        return ret;
    }
};

int main() {
    SimpleStructBase objBase;
    objBase.intPointer = new int(42);

    SimpleStructMng objMng = SimpleStructMng::CreateStruct(objBase);

    std::cout << "Base object: " << *objBase.intPointer << "\n";
    std::cout << "Managed object: " << *objMng.intPointer << "\n";

    return 0;
}

In the end of the CreateStruct, MSVC 2019 compiler (as well as gcc) for some reason first clears the object ret (also removing the only reference in ret.mem smart pointer) and then returns the object from the function. Of course, ret.mem becomes unavailable. Interesting that MSVC 2022 doesn't do that and everything works fine.

How can I change the program so it doesn't crash even in MSVC 2019/gcc? The only restriction is that the SimpleStructBase structure should keep unchanged.

最新文章