class Common
{
public:
Common()
{
std::cout << "Common::Common" << std::endl;
}
Common(const Common &r)
{
std::cout << "Common::Common copy-constructor" << std::endl;
}
~Common()
{
std::cout << "Common::~Common" << std::endl;
}
};
class BitCopy
{
public:
BitCopy()
: m_p(new Common)
{
std::cout << "BitCopy::BitCopy" << std::endl;
}
~BitCopy()
{
std::cout << "BitCopy::~BitCopy" << std::endl;
if (m_p) {
delete m_p;
m_p = NULL;
}
}
private:
Common *m_p;
};
int main()
{
BitCopy a;
BitCopy b(a);
return 0;
}
log如下:
Common::Common
BitCopy::BitCopy
BitCopy::~BitCopy
Common::~Common
BitCopy::~BitCopy
Common::~Common
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001f4e010 ***
已放弃 (核心已转储)
class ValueCopy
{
public:
ValueCopy()
: m_p(new Common)
{
std::cout << "ValueCopy::ValueCopy" << std::endl;
}
ValueCopy(const ValueCopy &r)
: m_p(new Common(*r.m_p))
{
std::cout << "ValueCopy::ValueCopy copy-constructor" << std::endl;
}
~ValueCopy()
{
std::cout << "ValueCopy::~ValueCopy" << std::endl;
if (m_p) {
delete m_p;
m_p = NULL;
}
}
private:
Common *m_p;
};
int main()
{
ValueCopy c;
ValueCopy d(c);
return 0;
}
Common::Common
ValueCopy::ValueCopy
Common::Common copy-constructor
ValueCopy::ValueCopy copy-constructor
ValueCopy::~ValueCopy
Common::~Common
ValueCopy::~ValueCopy
Common::~Common
class A
{
public:
A()
: m_refCount(1)
{
std::cout << "A::A" << std::endl;
}
A(const A &r)
: m_refCount(1)
{
std::cout << "A::A copy-constructor" << std::endl;
}
~A()
{
std::cout << "A::~A" << std::endl;
}
void attach()
{
std::cout << "A::attach" << std::endl;
++m_refCount;
}
void detach()
{
if (m_refCount != 0) {
std::cout << "A::detach " << m_refCount << std::endl;
if (--m_refCount == 0) {
delete this;
}
}
}
private:
int m_refCount;
};
class B
{
public:
B()
: m_pA(new A)
{
std::cout << "B::B" << std::endl;
}
B(const B &r)
: m_pA(r.m_pA)
{
std::cout << "B::B copy-constructor" << std::endl;
m_pA->attach();
}
~B()
{
std::cout << "B::~B" << std::endl;
m_pA->detach();
}
private:
A* m_pA;
};
int main()
{
B e;
B f(e);
return 0;
}
A::A
B::B
B::B copy-constructor
A::attach
B::~B
A::detach 2
B::~B
A::detach 1
A::~A
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有