Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

c++ - std::vector destructor gives error

I have a class like this:

class Foo
{
public:
    Foo() {};

    ~Foo() {};

    void MyFunc(int a)
    {
        m_struct.my_vec.push_back(a);
    }

public:
    MyStructType m_struct;
}

and MyStructType is defined similar to this:

struct MyStructType
{
    std::vector<int> my_vec;
}

The problem is that when I instantiate the class as follows, I get a memory violation error for std::vector deallocation when the m_struct destructor is called:

void main()
{
    Foo f;
    f.m_struct.my_vec.push_back(10);
}

However, if I do it the following way, the result is the same, but I don't get any error:

int main()
{
    Foo f;
    f.MyFunc(10);
}

To me, the two methods should be identical. Given that the actual code is more complicated than the snippet above, I would prefer to make m_struct public and go with the first option. Any suggestions as why the first method gives error when vector is being deallocated?

Thanks!

UPDATE: I notices that the problem is in fact in dll_export, which I failed to mention above. I am generating a dll and using it in another project. If I drop dllexport and put the definitions of the functions (although empty) in the header file, it runs OK. But when I export my class and put the definitions in the cpp file, it is when it gives me the error. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remove this line : memset(&m_struct, 0, sizeof(m_struct);

It likely corrupts the vector in MyStructType. Why are you doing that ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...