测试代码
cpp
#include <iostream>
#include <map>
#include <memory>
class Socket_RowData
{
public:
Socket_RowData()
{
pin_num = 0;
}
~Socket_RowData()
{
/* std::cout<<"Socket_RowData::~Socket_RowData()"<<std::endl*/;
}
public:
void Clear()
{
pin_num = 0;
m_pin_status.clear();
}
public:
int pin_num;
std::map<int,int> m_pin_status;
};
class Socket_Data
{
public:
Socket_Data()
{
socketrow_num = 0;
}
~Socket_Data()
{
/*std::cout<<"Socket_Data::~Socket_Data()"<<std::endl*/;
}
public:
void Clear()
{
socketrow_num = 0;
m_socket_row.clear();
}
public:
//每个插座的排数
int socketrow_num;
std::map<int, Socket_RowData> m_socket_row;
};
class Board_IOData
{
public:
Board_IOData()
{
socket_num = 0;
std::cout<<"Board_IOData::Board_IOData()"<<std::endl;
}
Board_IOData(const Board_IOData& data)
{
socket_num = 0;
std::cout<<"Board_IOData::Board_IOData() copy construct"<<std::endl;
}
Board_IOData& operator=(const Board_IOData& data)
{
socket_num = 0;
std::cout<<"Board_IOData::Board_IOData() assign construct"<<std::endl;
return *this;
}
~Board_IOData()
{
std::cout<<"Board_IOData::~Board_IOData()"<<std::endl;
}
public:
void Clear()
{
socket_num = 0;
m_socket_map.clear();
}
public:
//插座总数
int socket_num;
std::map<int,Socket_Data> m_socket_map;
};
void Test1()
{
std::cout<<"Test1() begin"<<std::endl;
{
//没有使用智能指针情形
std::cout<<"debug 1"<<std::endl;
Board_IOData board_iodata1;
std::map<int,Board_IOData> map1;
map1.insert(std::make_pair(1,board_iodata1));
std::cout<<"debug 2"<<std::endl;
map1.clear();
std::cout<<"debug 3"<<std::endl;
}
std::cout<<"debug ============="<<std::endl;;
{
//使用智能指针情形
std::cout<<"debug 4"<<std::endl;
std::shared_ptr<Board_IOData> board_iodata2(new Board_IOData);
std::map<int,std::shared_ptr<Board_IOData> > map2;
map2.insert(std::make_pair(1,board_iodata2));
std::cout<<"debug 5"<<std::endl;
map2.clear();
std::cout<<"debug 6"<<std::endl;
}
std::cout<<"Test1() end"<<std::endl;
}
int main()
{
Test1();
return 0;
}
bash
[banting@localhost test]$ g++ -g -std=c++11 -g test.cpp -o test
[banting@localhost test]$ ./test
Test1() begin
debug 1
Board_IOData::Board_IOData()
Board_IOData::Board_IOData() copy construct
Board_IOData::Board_IOData() copy construct
Board_IOData::~Board_IOData()
debug 2
Board_IOData::~Board_IOData()
debug 3
Board_IOData::~Board_IOData()
debug =============
debug 4
Board_IOData::Board_IOData()
debug 5
debug 6
Board_IOData::~Board_IOData()
Test1() end
[banting@localhost test]$
测试结果
没使用智能指针比使用智能指针在插入map时多了两次复制构造函数调用,增加数据拷贝的开销