Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This approach should be safe on all C++ implementations.</p> <p>Note, however, that if you know your platform's memory alignment requirements, you may be able to do better than this. In particular, if you know that memory allocations are aligned to 2 bytes or greater (many platforms use 8 or 16 bytes), you can use the lower bit of the pointer as a flag:</p> <pre><code>class Chunk { //... uintptr_t ptr; }; // In your get function: if ( (ptr &amp; 1) == 0 ) { return ((uint32_t *)ptr)[index]; } else { return *((uint32_t *)(ptr &amp; ~(uintptr_t)0); } </code></pre> <p>You can further reduce space usage by using a custom allocation method (with placement new) and placing the pointer immediately after the class, in a single memory allocation (ie, you'll allocate room for <code>Chunk</code> and either the mask or the array, and have <code>ptr</code> point immediately after <code>Chunk</code>). Or, if you know most of your data will have the low bit off, you can use the <code>ptr</code> field directly as the fill-in value:</p> <pre><code>} else { return ptr &amp; ~(uintptr_t)0; } </code></pre> <p>If it's the high bit that's usually unused, a bit of bit shifting will work:</p> <pre><code>} else { return ptr &gt;&gt; 1; } </code></pre> <p>Note that this approach of <a href="http://en.wikipedia.org/wiki/Tagged_pointer" rel="nofollow">tagging pointers</a> is unportable. It is only safe if you can ensure your memory allocations will be properly aligned. On most desktop OSes, this will not be a problem - malloc already ensures some degree of alignment; on Unixes, you can be absolutely sure by using <code>posix_memalign</code>. If you can obtain such a guarentee for your platform, though, this approach can be quite effective.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload