Note that there are some explanatory texts on larger screens.

plurals
  1. POUsage Issue of std::align
    text
    copied!<p>Consider the following code:</p> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; #include &lt;cstdio&gt; using namespace std; // Visual Studio 2012 don't have alignof as a keyword. #define alignof(type) __alignof(type) #define TEST_TYPE int int main(int, char*[]) { TEST_TYPE i; void* pv = &amp;i; size_t space = 100; // Just some big number. size_t alignment = alignof(TEST_TYPE); cout &lt;&lt; "Alignment of int: " &lt;&lt; alignment &lt;&lt; endl; cout &lt;&lt; "Is 'i' aligned: " &lt;&lt; (size_t(&amp;i) % alignment == 0 ? "true" : "false" ) &lt;&lt; endl; if ( align(alignment, sizeof(TEST_TYPE), pv, space) ) { TEST_TYPE* p = reinterpret_cast&lt;TEST_TYPE*&gt;(pv); cout &lt;&lt; "Moved pointer " &lt;&lt; (size_t(p) - size_t(&amp;i)) &lt;&lt; " bytes" &lt;&lt; endl; cout &lt;&lt; "Is 'p' aligned: " &lt;&lt; (size_t(p) % alignment == 0 ? "true" : "false" ) &lt;&lt; endl; } else { cout &lt;&lt; "Can't align 'i'" &lt;&lt; endl; } return 0; } </code></pre> <p>It creates an (properly aligned) integer and then calls std::align with the address of the integer. The output I get is:</p> <p>Alignment of int: 4 <br/> Is 'i' aligned: true <br/> Moved pointer 4 bytes <br/> Is 'p' aligned: true <br/></p> <p>indicating that the pointer is moved, even though the address is already properly aligned. However, the documentation (<a href="http://en.cppreference.com/w/cpp/memory/align" rel="nofollow">http://en.cppreference.com/w/cpp/memory/align</a>) says it <em>"... modifies the ptr to point to the first possible address of such aligned storage..."</em> but wouldn't that mean the pointer should be unchanged?</p> <p>So my question: Will the third argument to std::align (the pointer) always be changed to be one <em>size</em> greater if the argument pointer already is aligned?</p> <p><strong>EDIT</strong></p> <p>Also, if the pointer is NOT changed then will not the example in <a href="http://www.cplusplus.com/reference/memory/align/?kw=align" rel="nofollow">http://www.cplusplus.com/reference/memory/align/?kw=align</a> enter an infinite loop?</p> <p><strong>2nd EDIT</strong></p> <p>NOTE The link has been updated and the possible problem no longer occurs.</p>
 

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