class MyPoint
{
public:
MyPoint();
MyPoint(const MyPoint &c);
~MyPoint();
MyPoint& operator = (const MyPoint &right);
private:
CalculationPoint *CalculateInformation = nullptr;
//std::shared_ptr<CalculationPoint> CalculateInformation;
};
类声明含有默认构造函数、拷贝构造函数、析构函数、copy assignment操作符,CalculationPoint是自定义的另一个类。
MyPoint::MyPoint()
{
}
MyPoint::MyPoint(const MyPoint &c)
{
if(c.CalculateInformation != nullptr)
this->CalculateInformation = new CalculationPoint(*c.CalculateInformation);
//this->CalculateInformation.reset(new CalculationPoint(*c.CalculateInformation));
}
MyPoint::~MyPoint()
{
if(this->CalculateInformation != nullptr){
delete this->CalculateInformation;
//this->CalculateInformation.reset();
this->CalculateInformation = nullptr;
}
}
MyPoint& MyPoint::operator = (const MyPoint &right)
{
if(this != &right){
if(right.CalculateInformation != nullptr)
this->CalculateInformation = new CalculationPoint(*right.CalculateInformation);
//this->CalculateInformation.reset(new CalculationPoint(*right.CalculateInformation));
}
return *this;
}
经过Valgrind后报错
==315== 8,240 (136 direct, 8,104 indirect) bytes in 1 blocks are definitely lost in loss record 330 of 345
==315== at 0x4C2E0EF: operator new(unsigned long) (vg_replace_malloc.c:333)
==315== by 0x47EE60: MyPoint::MyPoint(MyPoint const&) (mypoint.cpp:185)
==315== by 0x443643: _ZN9__gnu_cxx13new_allocatorI7MyPointE9constructIS1_IRS1_EEEvPT_DpOT0_ (in /home/zpf/zpf/docker_run/execute/ServiceRealtime)
==315== by 0x43DA52: _ZNSt16allocator_traitsISaI7MyPointEE9constructIS0_IRS0_EEEvRS1_PT_DpOT0_ (alloc_traits.h:530)
==315== by 0x438820: void std::vector<MyPoint, std::allocator<MyPoint> >::emplace_back<MyPoint&>(MyPoint&) (vector.tcc:96)
==315== by 0x42AA95: Model_Class::load_model() (model_class.cpp:292)
==315== by 0x428B18: Model_Class::Model_Class(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (model_class.cpp:54)
==315== by 0x4226E8: main (main.cpp:87)
==315== LEAK SUMMARY:
==315== definitely lost: 136 bytes in 1 blocks
==315== indirectly lost: 8,104 bytes in 80 blocks
==315== possibly lost: 1,045,120 bytes in 3,266 blocks
==315== still reachable: 2,123,964 bytes in 21,602 blocks
==315== suppressed: 0 bytes in 0 blocks
将所有的指针改为std::shared_ptr后成功解决,智能指针处的注释拿掉即可。
==6153== LEAK SUMMARY:
==6153== definitely lost: 0 bytes in 0 blocks
==6153== indirectly lost: 0 bytes in 0 blocks
==6153== possibly lost: 138,560 bytes in 433 blocks
==6153== still reachable: 534,451 bytes in 3,470 blocks
==6153== suppressed: 0 bytes in 0 blocks
教训总结:指针内存泄露很难找,尽量多使用c++11新标准的智能指针来避免。