jeudi 29 avril 2021

Passing smart pointer to function through non smart pointer argument

Consider the following function:

void example(void **ptr){
    std::cout << *ptr << "\n";                   // pointer value
    std::cout << ptr << "\n";                    // pointer address
    std::cout << **reinterpret_cast<int**>(ptr); // value
}

The function signature cannot be changed.

Is the following code valid, or should I use raw pointers?

int main() 
{
    std::unique_ptr<int> x = std::make_unique<int>(20);
    std::cout << x.get() << "\n";                 // pointer value
    std::cout << &x << "\n";                      // pointer address
    example(reinterpret_cast<void**>(&x));
}

Live sample

Aucun commentaire:

Enregistrer un commentaire