Search code examples
c++castingstdvectorunique-ptrstd

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));
    }
    auto 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?


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.