64,652
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <stack>
using namespace std;
class A
{
public:
A(int element)
{
a = element;
cout<<"construct"<<a<<endl;
}
~A()
{
cout<<"end"<<a<<endl;
}
void print()
{
cout<<a<<endl;
}
private:
int a;
};
int main()
{
A a1(1),a2(2);
stack<A> stack1;
stack1.push(a1);
stack1.push(a2);
A &data = stack1.top();
stack1.pop();
data.print();
return 0;
}
A test(A TT)
{
TT.print();
return TT;
}
在加点,看看调用这个要做几次拷贝
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
class A
{
public:
A(const A& T)
{
this->a = T.a;
cout<<"调用拷贝构造"<<endl;
this->pbuff = new char[20];
memset(this->pbuff,0,20);
strcpy(this->pbuff,T.pbuff);
}
A(int element)
{
a = element;
pbuff = new char[20];
memset(pbuff,0,20);
sprintf(pbuff,"test %d",a);
cout<<"construct"<<a<<endl;
}
~A()
{
cout<<"end"<<a<<endl;
delete pbuff;
}
void print()
{
cout<<a<<","<<pbuff<<",0x"<<this<<endl;
}
private:
int a;
char* pbuff;
};
int main()
{
{
A a1(1),a2(2);
a1.print();
a2.print();
stack<A> stack1;
stack1.push(a1);
stack1.push(a2);
A &data = stack1.top();
//data.print();
stack1.pop();
data.print();
}
return 0;
}
加了点代码,加深理解,push这里是发生了拷贝构造,加了个buff,pop后访问就有问题了,内存释放了
你写的可以访问,是对象析构后,内存还没有马上被重新写入,你可以在pop加一句char*p = new char[10000] 然后print试试