分类: C/C++
2015-09-06 16:18:40
class
User
{
...
string GetName();
void
AddFriend(User& newFriend);
private
:
typedef
vector UserCont;
UserCont friends_;
UserDatabase* pDB_;
};
void
User::AddFriend(User& newFriend)
{
// Add the new friend to the database
pDB_->AddFriend(GetName(), newFriend.GetName());
// Add the new friend to the vector of friends
friends_.push_back(&newFriend);
}
实现异常安全的代码,上述AddFriend的两条语句都会抛出异常,一种解决方案:
class
VectorInserter
{
public
:
VectorInserter(std::vector& v, User& u)
: container_(v), commit_(
false
)
{
container_.push_back(&u);
}
void
Commit()
throw
()
{
commit_ =
true
;
}