Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast vector data of unique_ptr to pointer to const pointer

I have a std::vector of std::unique_ptr and I want to call a function from an API that takes a pointer to const pointer. Would it be correct to cast its data() to that type?

This example program seems to work in GCC:

#include <vector>
#include <iostream>
#include <memory>

class A
{
public:
    A(int n) : n(n) {}
    int n;
};

int main()
{
    const int num = 3;
    std::vector<std::unique_ptr<A>> v;
    for (int i = 0; i < num; i++)
    {
        v.push_back(std::make_unique<A>(i));
    }
    A * const * vPtr = (A * const *) v.data();
    for (int i = 0; i < num; i++)
    {
        std::cout << vPtr[i]->n << std::endl;
    }
    return 0;
}

Does the standard guarantee that the layout of std::unique_ptr is just a pointer, and thus this is safe to do?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No, this is an aliasing violation. A std::unique_ptr is not a raw pointer.

"seems to work in GCC" is not safe in C++. You code has undefined behaviour, and "seems to work" is the worst symptom, because it can suddenly become "breaks in the most inopportune way" with no notice.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading