user3667089 user3667089 - 1 year ago 194
C++ Question

How to cast an int unique_ptr into a void unique_ptr?

Suppose I have a function that looks like

void *func(){
int *a = new int;
*a = 1;

void *b = a;
return b;

and in my main function I can use it like

int *test = reinterpret_cast<int *>(func());
std::cout << test[0] << std::endl;
delete test;

and it will print the correct result. Lets say I want to use unique_ptr for my function so it becomes

std::unique_ptr<void> func(){
std::unique_ptr<int> a(new int);
*a = 1;

std::unique_ptr<void> b = a; // does not compile
return b;

It throws a compilation error

error: conversion from ‘std::unique_ptr<int>’ to non-scalar type ‘std::unique_ptr<void>’ requested

What should I do to make unique_ptr work in this scenario?

Answer Source

A unique_ptr holds a deleter that is responsible for executing a delete-expression (or delete[]-expression) on the pointer, when the lifetime of the unique_ptr ends.

But the expression delete p when p is a void*, is invalid.

So the default functionality of unique_ptr does not support void*. I am not sure if it is explicitly forbidden or not to have a unique_ptr<void>. But if it's not forbidden, then trying to define a custom deleter to do this work, would not be smart.

Instead fix the design.

Don't throw away the type information in the first place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download