开发者

Memory management of vector

开发者 https://www.devze.com 2023-04-10 15:42 出处:网络
I have a C++ class with a private \"pointer to vector\" member pV, I assign a new vector to it in the constructor...

I have a C++ class with a private "pointer to vector" member pV, I assign a new vector to it in the constructor...

pV = new vector<FMCounter>(n, FMCounter(arg1))>;

However when I delete in the destructor of the class

delete pV;

I get a segfault and a message that I'm trying to free pv that wasn't allocated in the first place. I checked that pV->size() was 4K something, so I am sure it was allocat开发者_StackOverflow社区ed memory by new.


Pointer members with ownership semantics (allocating in constructor and deallocating in destructor) usually require to write a custom copy constructor and assignment operator (usually known as the Rule of Three), as the compiler generated ones will just copy the pointer member and not its underlying object. So if you at some point copy your containing object, you end up with two objects having the same pointer as member and the one destroyed secondly tries to delete an already deleted pointer.

At the simplest you should make sure your copy constructor does something like

TheClass::TheClass(const TheClass &rhs)
    : pV(new vector<FMCounter>(*rhs.pV))
{
}

and your assigment operator does something like

TheClass& TheClass::operator=(const TheClass &rhs)
{
    *pV = *rhs.pV
    return *this;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消