vendredi 2 août 2019

Returning std::unique_ptr containing custom deleter

My application compiler could only supports upto c++11.

Below is a snip code of my project and function get_conn() returns std::unique_ptr with custom deleter (deleter needs two arguments). I'm using auto keyword for return type but it gives error like if is compiled with c++11 (compiles fine with c++14)

error: ‘get_conn’ function uses ‘auto’ type specifier without trailing return type

Sample code for demonstration:

#include <iostream>
#include <functional>
#include <memory>
using namespace std;


// Dummy definition of API calls                                                                                                             
int* open_conn (int handle)
{
  return new int;
}
void close_conn (int handle, int *conn)
{
}

auto
get_conn (int handle)
{
  // API call                                                                                                                                
  int* conn = open_conn (handle);

  auto delete_conn = [](int *conn, int handle)
      {
        // API call                                                                                                                          
    close_conn (handle, conn);
    delete conn;
      };
  auto delete_binded = std::bind (delete_conn, std::placeholders::_1, handle);
  return std::unique_ptr<int, decltype(delete_binded)> (conn, delete_binded);
}

int main()
{
  int handle = 2; // suppose                                                                                                                 
  auto c = get_conn (handle);
  if (!c)
    cout << "Unable to open connection\n";

  return 0;
};

How can I replace auto keyword with actual return type of std::unique_ptr to compatible code with c++11 ?

I tried with below return type but failed

std::unique_ptr<int, void(*)(int *,int)>
get_conn (int handle) 

Aucun commentaire:

Enregistrer un commentaire