我有一个
std::vector
的 std::unique_ptr
,我想从 API 调用一个函数,该函数采用指向 const 指针的指针。将其 data()
转换为该类型是否正确?
这个示例程序似乎可以在 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;
}
标准是否保证
std::unique_ptr
的布局只是一个指针,因此这样做是安全的?
不,这是违反别名的行为。
std::unique_ptr
不是原始指针。
“似乎在 GCC 中工作”在 C++ 中不安全。您的代码具有未定义的行为,“似乎有效”是最糟糕的症状,因为它可能会在没有通知的情况下突然变成“以最不合适的方式中断”。