-1

ポインター演算を使用するために、void ポインターの型は複数回変換されます。

データを含むベクターは外部ソースから取得され、そのデータにアクセスするための void ポインターを返します。さらに、ストライドも外部オブジェクトによって与えられ、アライメント要件に注意を払います。例を簡潔にするために、この 2 つの事実を完全には反映していません。

// Example data from external source.
struct Data {
    float x;
    float y;

    Data() : x(5), y(8) {}
};

// Example vector from external source.
size_t elements = 3;
std::vector<Data> list;
list.resize(elements);

// Pointer conversions.
const void * voidPointer = list.data(); // The external object containing the vector returns a void pointer.
const uint8_t * countPointer = static_cast<const uint8_t*>(voidPointer);

// Pointer arithmetics.
unsigned stride = sizeof(Data); // The external object returning the stride heeds alignment requirements.
for (size_t counter = 0; counter < elements; ++counter, countPointer += stride) {
    const float * pointsToFloatX = reinterpret_cast<const float*>(countPointer);
    printf("%f, ", *pointsToFloatX); // Expecting something like 5.0000, 5.0000, 5.0000
}

への変換は、ポインターの型のみが変換されるため、ポインターが指してuint8_tいる ( ) データには影響しませんか?float

インクリメントされますが、なぜconst動作するのですか? ポインタが指しているデータが変更されない可能性があるということですかcountPointer?const

ループ内で変換するreinterpret_cast<const float*>代わりに使用する必要があるのはなぜですか?static_cast<const float*>countPointer

4

1 に答える 1

2

への変換は、ポインターの型のみが変換されるため、ポインターが指してuint8_tいる ( ) データには影響しませんか?float

それは正しい。ただし、ポインターをキャストするときは、アラインメント要件があることに注意してください。また、 ;を&list指すことに注意してください。配列を取得するためにvector<Data>使用します。list.data()Data*

インクリメントされますが、なぜconst動作するのですか? ポインタが指しているデータが変更されない可能性があるということですかcountPointer?const

はい。float * constポインター自体を定数にするかconst float * const、定数データへの定数ポインターを取得するために書き込みます。

ループ内で変換するreinterpret_cast<const float*>代わりに使用する必要があるのはなぜですか?static_cast<const float*>countPointer

互換性のある型は でキャストできstatic_cast、他のユーザーは を使用できますreinterpret_castvoid*他のものと互換性があります。reinterpret_cast自分が何をしているのかをよく知っている場合を除き、使用は避けてください。

于 2015-07-26T09:58:45.457 に答える