/*
智能指针中 的vector < boost::shared_ptr<Student> >::const_iterator 只是 指针的const 而不是 object
如果是 const object那么定义数组的时候要 vector < boost::shared_ptr<const Student> >,
更详细的说明在 more Efficient C++ 第28条
*/
#pragma once
#include <string>
#include <ostream>
#include <iostream>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/make_shared.hpp"
#include "boost/foreach.hpp"
#define foreach BOOST_FOREACH
#define auto_t BOOST_AUTO
using namespace boost;
using namespace std;
class Student
{
string m_sName;
string m_sId ;
public:
Student(std::string const& sName, std::string const& sId)
:m_sName(sName)
,m_sId(sId) {}
~Student() {std::cout <<m_sName << "执行析构函数." << std::endl;};
string const& getName() const { return m_sName;} ;
string const& getId() const { return m_sId; } ;
void setName(std::string const& sName) { m_sName = sName; } ;
};
int main()
{
/*--------------简单的测试---------------*/
//shared_ptr<Student> pStudent(new Student("Leon Anavi", "F010203"));
//更简洁高效的方式 auto
auto pStudent = boost::make_shared<Student>("aa", "F010203");
std::cout << "Student: " << pStudent->getName() << " " << pStudent->getId() << std::endl;
/*--------------容器测试----------------*/
vector< boost::shared_ptr<Student> > va(1);
va[0] = boost::make_shared<Student>("bb", "F010203");
va.push_back( boost::make_shared<Student>("cc", "F010203"));
vector < boost::shared_ptr<Student> >::const_iterator ww = va.begin();
for (;ww != va.end(); ++ww)
{
std::cout << (*ww)->getName() << std::endl;
}
foreach( auto w = *va.begin(),va)
{
std::cout << (*w).getName() << endl;
}
return 0;
}
boost::shared_ptr(待续)
最新推荐文章于 2025-08-06 12:50:44 发布