2

I am trying to pass a std::unique_ptr (of array type) through a std::bind and I am getting compiler errors.

#include <functional>
#include <memory>
#include <stdio.h>
#include <string.h>

class PrintClass 
{ 
public:
    void printFunc(std::unique_ptr<char[]> text) 
    {
        printf("Printed text %s\n", text.get());
    }
};


int main() 
{
    std::unique_ptr<PrintClass> printObj(new PrintClass);
    std::unique_ptr<char[]> buffer(new char[1024]);
    strcpy(buffer.get(),"Test data"); 
    std::function<void()> fn = std::bind(&PrintClass::printFunc,
        printObj.get(), std::move(buffer));
    fn();
}

This returns the following compiler error:

test.cpp: In function int main(): test.cpp:21:98: error: conversion from std::_Bind_helper<false, void (PrintClass::*)(std::unique_ptr<char []>), PrintClass*, std::unique_ptr<char [], std::default_delete<char []> > >::type {aka std::_Bind<std::_Mem_fn<void (PrintClass::*)(std::unique_ptr<char []>)>(PrintClass*, std::unique_ptr<char []>)>} to non-scalar type std::function<void()> requested std::function fn = std::bind(&PrintClass::printFunc,printObj.get(), >std::move(buffer));

I am compiling with:

g++ -std=c++11 ...

I could use raw pointers but I then run the risk of memory leaks. So how do I pass ownership of my buffer through the std::bind interface?

I am using strings here to illustrate my point. My real problem involves passing binary memory buffers which I want to ensure do not leak.

Please ignore the use of strcpy without array bounds checking, I just wanted to knock something together to illustrate my problem.

doron
  • 27,972
  • 12
  • 65
  • 103
  • 2
    Related to [Is there a reference_wrapper<> for rvalue references?](http://stackoverflow.com/questions/5126219/is-there-a-reference-wrapper-for-rvalue-references?lq=1) – Jarod42 Jun 10 '14 at 11:40
  • 2
    Since unique_ptr does not have a copy constructor, shouldn't your function take an rvalue reference ? – Quentin Jun 10 '14 at 11:40
  • Related enough to be a dupe, I think. Good question, though. – Lightness Races in Orbit Jun 10 '14 at 11:42
  • 1
    There's a secondary issue, in that you're attempting to assign a move-only `bind` (due to the unique_ptr's being stored at bind time) to a `std::function`, which requires that the function objects be copyable. – Dave S Jun 10 '14 at 11:52

0 Answers0