#include <vector>
#include <iostream>
#include <memory>
using namespace std;
class A
{
static int k;
public:
A(){k++ ; cout << "constructor : " <<k<< endl;};
~A(){k--; cout << "destructor : " << k <<endl;};
void show() { cout<<"current value of k = "<<k<<endl; }
};
int A::k = 0;
int main( )
{
vector<A> test;
test.push_back(A());
test.emplace(test.end(), A());
test[0].show();
cout<<test.size()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
构造函数:1
析构函数:0
构造函数:1
析构函数:0
析构函数:-1
当前值k = -1
2
析构函数:-2
析构函数:-3
为什么析构函数被调用了太多次,因为它应该被调用两次,因为构造函数只被调用两次?如何避免这种情况?
以下代码导致运行时错误.
每个都shared_ptr拥有相同的内存,但每个内存的数量仍然是一个.
因此,每个共享指针都是不同的,所以当它们超出范围时,它们会尝试释放块,这会导致损坏堆.我的问题是如何避免这种情况?
只想添加这样的声明
shared_ptr<int> x(p);
Run Code Online (Sandbox Code Playgroud)
不可谈判我必须申报.
#include <iostream>
#include <memory>
using namespace std;
int main ()
{
int* p = new int (10);
shared_ptr<int> a (p);
shared_ptr<int> b (p);
shared_ptr<int> c (p);
shared_ptr<int> d (p);
cout<<"Count : "<<a.use_count()<<endl;
cout<<"Count : "<<b.use_count()<<endl;
cout<<"Count : "<<c.use_count()<<endl;
cout<<"Count : "<<d.use_count()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 即使在使用unique_ptr之后,构造函数和析构函数调用也不匹配.有没有办法让构造函数和析构函数调用匹配,否则会有内存泄漏.
#include <iostream>
using namespace std;
class P
{
public:
P() { cout<<"P()\n"; }
virtual ~P() { cout<<"~P()\n"; }
};
class D: public P
{
P *q;
public:
D(P *p):q(p) { cout<<"D()\n"; }
~D() { cout<<"~D()\n"; }
};
class A: public D
{
public:
A(P *p):D(p) { cout<<"A()\n"; }
~A() { cout<<"~A()\n"; }
};
class B: public D
{
public:
B(P *p):D(p) { cout<<"B()\n"; }
~B() { cout<<"~B()\n"; }
};
int main()
{
P *p = new B(new A(new P())); …Run Code Online (Sandbox Code Playgroud) #include<iostream>
#include<memory>
using namespace std;
int main()
{
unique_ptr<int> p(new int);
*p = 10;
cout<<*p<<endl;
p = NULL;
if(p)
cout<<"It's NOT NULL\n";
else
cout<<"It's NULL NOW\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
//当我为p分配NULL时,程序完成后,它将删除//有NULL的p.虽然删除NULL不会导致任何问题,但是之前由p //保留的内存不会被释放.我对么 .