jeudi 16 mars 2023

Smart Pointers and Exception

A practice question on C++ primer:

one easy way to make sure resources are freed is to use smart pointers.

Imagine we're using a network library that is used by both C and C++. Programs that use this library might contain code such as:

struct connection
{
    string ip;
    int port;
    connection(string i, int p) :ip(i), port(p) {};
};  // represents what we are connecting to

struct destination
{
    string ip;
    int port;
    destination(string i, int p) :ip(i), port(p) {};
};  // information needed to use the connection

void disconnect(connection c)
{
    cout << "Scoket(" << c.port << "," << c.port << ") disconnect" << endl;
}  //close the given connection

connection connect(destination* pDest)
{
    shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port), disconnect );
    cout << "Scoket(" << pConn->ip << "," << pConn->port << ") connect" << endl;
    return *pConn;
}  // open the connection


void f(destination& d)
{
    connection c = connect(&d);
}

compile error:

error C2661: 'std::shared_ptr<connection>::shared_ptr': no overloaded function takes 2 arguments.

What's wrong with the code?

Aucun commentaire:

Enregistrer un commentaire