boost::shared_ptr(待续)

本文深入探讨了C++中智能指针的应用,特别是vector<boost::shared_ptr<Student>>类的使用及注意事项。通过对比const object与non-const object的差异,阐述了如何更高效地使用boost库中的make_shared函数。文章还详细解释了容器测试中的迭代器使用与遍历方法,并提供了具体的代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 
智能指针中 的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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值