Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an int unique_ptr into a void unique_ptr?

Tags:

c++

c++11

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?

like image 928
user3667089 Avatar asked Feb 06 '23 18:02

user3667089


1 Answers

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.

like image 72
Cheers and hth. - Alf Avatar answered Feb 08 '23 16:02

Cheers and hth. - Alf