Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

c++ - Treat C cstyle array as std::array

Is there any safe and standard compliant way to treat a C style array as an std::array without copying the data into a new std::array?

This clearly doesn't compile, but is the effect I would like (my real use is more complicated but this short sample should show what I'd like to do). I guess a reinterpret_cast would "work" but probably isn't safe?

#include <array>

int main()
{
    int data[] = {1, 2, 3, 4, 5};

    // This next line is the important one, treating an existing array as a std::array
    std::array<int, 5>& a = data;
}

It feels like it ought to be possible as the data should be stored identically.

edit: To be clear I don't want to clear a new std::array, I want to refer to the existing data as one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As discussed in this post Is std::array<T, S> guaranteed to be POD if T is POD?

std::array<int, N> is POD and thus standard layout. As far as I understand the standard layout requirements, this means that the pointer to the object is identical to the pointer to the first member. Since std::array has no private/ protected members (according to http://en.cppreference.com/w/cpp/container/array), this should agree with the first element in the wrapped array. Thus something like

reinterpret_cast< std::array<int, 5>* >( &data )

is in my opinion guaranteed to work by the standard. I have to admit, though, that I sometimes have difficulties interpreting the standard language, so please correct me if I am wrong.

Regards Claas


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...