简体   繁体   English

std::vector.data() 是否在指针向量上以 null 结尾?

[英]Is std::vector.data() null-terminated on a vector of pointers?

I am using a C library in my C++ application.我在我的 C++ 应用程序中使用 C 库。 One of the functions needs a null-terminated array of pointers .其中一个函数需要一个null-terminated array of pointers

Since I am using C++, I am storing the elements of the array in a std::vector .由于我使用的是 C++,因此我将数组的元素存储在std::vector中。

I would like to know if it's safe to simply call data() on my vector and pass the result to the library function.我想知道简单地在我的向量上调用data()并将结果传递给库 function 是否安全。

Exemple:例子:

std::vector<struct A *> vec;

//library_function(struct A **array);
library_function(vec.data());

Of course, if I change the elements in the vector then the pointer returned by data() will be invalidated, but that is not an issue here (I can call the function again when updating the vector).当然,如果我更改向量中的元素,则data()返回的指针将失效,但这在这里不是问题(我可以在更新向量时再次调用 function)。

I am just afraid this might be undefined behavior, since I can't see anywhere mentioned that data() is terminated by a null pointer and not by random garbage.我只是担心这可能是未定义的行为,因为我看不到任何地方提到data()由 null 指针而不是随机垃圾终止。

The standard does say:该标准确实说:

const T* data() const noexcept;

Returns pointer to the underlying array serving as element storage.
The pointer is such that range [data(); data() + size()) is always a valid range

So there is a terminating element, but it doesn't say if that element is initialized and if it is, with what value.所以有一个终止元素,但它没有说明该元素是否已初始化,如果已初始化,其值是多少。

Is it specified somewhere else that I missed?它是在我错过的其他地方指定的吗?
Or do I have to allocate a raw array and null terminate it myself?还是我必须分配一个原始数组并 null 自己终止它?

A vector of pointers is null terminated if the last element of the vector is null. There is no extra null element after the last element (like there would be a null terminator character after the last element of a std::string ).如果向量的最后一个元素是 null,则指针向量是 null 终止。在最后一个元素之后没有额外的 null 元素(就像在std::string的最后一个元素之后会有一个 null 终止符)。 The last element of a vector isn't null automatically.向量的最后一个元素不会自动为 null。 If you need the last element to be null, then you must insert the null element.如果您需要最后一个元素是 null,那么您必须插入 null 元素。

Example:例子:

std::vector<A>  vec_of_struct(size);
std::vector<A*> vec_of_ptrs;
vec_of_ptrs.reserve(size + 1);
std::ranges::copy(
    std::views::transform(
        vec_of_struct,
        [](A& a) { return &a; }
    ),
    std::back_inserter(vec_of_ptrs)
);
vec_of_ptrs.push_back(nullptr); // null terminator pointer
library_function(vec_of_ptrs.data()); // C function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM