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 fromstd::_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 typestd::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.