//: C04:Noisy.h
// A class to track various object activities
#ifndef NOISY_H
#define NOISY_H
#include <iostream>
class Noisy
{
static long create, assign, copycons, destroy;
long id;
public:
Noisy() : id(create++)
{
std::cout << "d[" << id << "]";
}
Noisy(const Noisy& rv) : id(rv.id)
{
std::cout << "c[" << id << "]";
copycons++;
}
Noisy& operator=(const Noisy& rv)
{
std::cout << "(" << id << ")=[" <<
rv.id << "]";
id = rv.id;
assign++;
return *this;
}
friend bool
operator<(const Noisy& lv, const Noisy& rv)
{
return lv.id < rv.id;
}
friend bool
operator==(const Noisy& lv, const Noisy& rv)
{
return lv.id == rv.id;
}
~Noisy() {
std::cout << "~[" << id << "]";
destroy++;
}
friend std::ostream&
operator<<(std::ostream& os, const Noisy& n)
{
return os << n.id;
}
friend class NoisyReport;
};
struct NoisyGen
{
Noisy operator()() { return Noisy(); }
};
// A singleton. Will automatically report the
// statistics as the program terminates:
class NoisyReport
{
static NoisyReport nr;
NoisyReport() {} // Private constructor
public:
~NoisyReport()
{
std::cout << "/n-------------------/n"
<< "Noisy creations: " << Noisy::create
<< "/nCopy-Constructions: "
<< Noisy::copycons
<< "/nAssignments: " << Noisy::assign
<< "/nDestructions: " << Noisy::destroy
<< std::endl;
}
};
// Because of these this file can only be used
// in simple test situations. Move them to a
// .cpp file for more complex programs:
long Noisy::create = 0, Noisy::assign = 0,
Noisy::copycons = 0, Noisy::destroy = 0;
NoisyReport NoisyReport::nr;
#endif // NOISY_H ///:~
int main()
{
const int quantity = 10;
// Create raw storage and cast to desired type:
Noisy* np =
(Noisy*)new char[quantity * sizeof(Noisy)];
raw_storage_iterator<Noisy*, Noisy> rsi(np);
for(int i = 0; i < quantity; i++)
*rsi++ = Noisy(); // Place objects in storage
cout << endl;
copy(np, np + quantity,
ostream_iterator<Noisy>(cout, " "));
cout << endl;
// Explicit destructor call for cleanup:
for(int j = 0; j < quantity; j++)
(&np[j])->~Noisy();
// Release raw storage:
delete (char*)np;
int i;
cin >> i;
} ///:~
*rsi++ = Noisy(); 为什么调用copy构造函数,而不是=的重载函数?
最新推荐文章于 2018-09-02 13:42:21 发布
本文介绍了一个名为Noisy的C++类,该类用于跟踪对象的创建、复制构造、赋值及销毁等行为,并通过一个示例展示了如何手动管理此类对象的内存,包括分配、初始化、析构和释放。
308

被折叠的 条评论
为什么被折叠?



