Convert std :: shared_ptr <char> to std :: shared_ptr <unsigned char>

Is there a good way to convert shared_ptr<char>to shared_ptr<unsigned char>?

I came up with the following, but it does not look very clean.

int main(int argc, char** argv)
{
    std::shared_ptr<char> p1 = std::make_shared<char>();

    std::shared_ptr<unsigned char> p2 = std::shared_ptr<unsigned char>(
        reinterpret_cast<unsigned char*>(p1.get()),
        [p1](unsigned char*) {});
}
+4
source share
1 answer

There is a ready-made function for what you are doing reinterpret_pointer_cast:

std::shared_ptr<unsigned char> p2 =
    std::reinterpret_pointer_cast<unsigned char>(p1);

As a result, the pointer exchanges property with the original pointer.

In contrast, your own code ends with two separate ownership groups. If the original group dies first, your new pointer will be visible!

p1.get(), , . , (. ):

std::shared_ptr<unsigned char> p2(p1, reinterpret_cast<unsigned char*>(p1.get()));

, p1, , .

+6

Source: https://habr.com/ru/post/1672876/


All Articles