|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
struct connection
{
std::string ip;
int port;
connection(std::string i, int p) : ip(i), port(p) {}
};
struct destination
{
std::string ip;
int port;
destination(std::string i, int p) : ip(i), port(p) {}
};
connection connect(destination* pDest)
{
std::shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port));
std::cout << "creating connection(" << pConn.use_count() << ")" << std::endl;
return *pConn;
}
void disconnect(connection pConn)
{
std::cout << "connection close(" << pConn.ip << ":" << pConn.port << ")" << std::endl;
}
void end_connection(connection* pConn)
{
disconnect(*pConn);
}
void f(destination &d)
{
connection conn = connect(&d);
std::shared_ptr<connection> p(&conn, end_connection);这里是指没有对conn引用时候删除,但删除的是conn还是p.为什么不是删除的p?这里比较乱,有点不解?
std::cout << "connecting now(" << p.use_count() << ")" << std::endl;
}
int main()
{
destination dest("220.181.111.111", 10086);
f(dest);
return 0;
}
p 是一个智能指针,管理着 conn 的生命周期。
当 p 被销毁或者没有其他 shared_ptr 指向 conn 时,会调用 end_connection 函数而不是直接删除 conn。
end_connection 函数调用 disconnect 函数,但不会删除 conn 对象本身,因为 conn 是一个栈上的局部变量,它会在 f 函数结束时自动销毁。
这种用法是一种管理资源的方式,确保即使发生异常,资源也能被正确释放。但是,这里有一个潜在的问题:p 指向的是一个栈上的对象 conn。当 f 函数结束时,conn 会被销毁,但 p 可能仍然存在(尽管在这个特定的例子中,它在 f 结束时也会被销毁)。如果 p 被复制到函数 f 的外部,那么它将指向一个已经销毁的对象,这会导致未定义行为。
通常,我们不建议让 std::shared_ptr 管理栈上的对象,而是应该直接管理动态分配(使用 new)的对象。这样可以避免潜在的悬挂指针问题。
|
|