2017-01-28 3 views
2

私はメモリアライメントがC++でどのように機能するかを理解しようとしています。アライメントは、ポインタ内の末尾のゼロの数とどのように関連していますか?

正しく理解すれば、nがポインタのバイナリ表現の末尾の0の数であれば、ポインタは2^nバイトに揃えられます。ただし、次のプログラム:

#include <bitset> 
#include <cstdint> 
#include <iostream> 
#include <climits> 
#include <cassert> 

template <typename T> 
std::size_t nTrailingZeros(const T* pointer) 
{ 
    assert(CHAR_BIT == 8); 
    std::bitset<8*sizeof(std::uintptr_t)> bits(reinterpret_cast<std::uintptr_t>(pointer)); 
    std::size_t nZeroes{}; 
    while (nZeroes < bits.size() && !bits[nZeroes]) 
    { 
     ++nZeroes; 
    } 
    return nZeroes; 
} 

struct alignas(64) A {int x;}; 

int main() 
{ 
    std::cout << "Alignment: "  << alignof (A)   << std::endl; 
    std::cout << "Trailing zeros: " << nTrailingZeros (new A) << std::endl; 
} 

出力:

アライメント:64個の 末尾のゼロ:私のコンピュータで4

私は間違っていますか?私は少なくとも6つの末尾のゼロを期待していますが、私は4つだけです(16バイトのアライメントを示唆しています)。

答えて

5

オーバーライドされたデータの動的メモリ割り当てはサポートされていません。残念なことですが、自分で整列されたメモリを取得し、それに新しいメモリを配置する必要があります。

サイドノート:bitsetは十分ではありません。 8*sizeof (uintptr_t)ビットが必要です。

+2

*まだ*サポートされていません。 C++ 17はこの穴を塞ぎます。 –

関連する問題