Note that there are some explanatory texts on larger screens.

plurals
  1. POConstant correctness
    primarykey
    data
    text
    <p>In the printMessage if you access the vector of a constant class using the index it works fine, but not with the the iterator (*itr). If the iterator is declared as constant_iterator then it works fine.</p> <p>Why? </p> <p>In both cases I am reading the data and not modifying the vector. Can someone shed some light? </p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;sstream&gt; //Set this define to enable the block to compile. #define WILL_WORK 1 #define WILL_NOT_WORK !WILL_WORK class TestMessage { public: TestMessage(){}; typedef std::vector&lt;int&gt; TestVec; typedef std::vector&lt;int&gt;::iterator TestItr; //The const iterator will work //typedef std::vector&lt;uint32_t&gt;::const_iterator TestItr; typedef std::vector&lt;int&gt;::size_type TestSize; TestVec m_testVector; }; void printMessage(const TestMessage &amp; tmessage) { std::ostringstream asciiMessage; asciiMessage &lt;&lt; tmessage.m_testVector.size() &lt;&lt; ","; #if WILL_NOT_WORK //This will not work // MS Visual Studio // error C2440: 'initializing' : cannot convert from // 'std::_Vector_const_iterator&lt;_Ty,_Alloc&gt;' to // 'std::_Vector_iterator&lt;_Ty,_Alloc&gt;' // GCC // error: conversion from // '__gnu_cxx::__normal_iterator&lt;const int*, // std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt;' // to non-scalar type // '__gnu_cxx::__normal_iterator&lt;int*, // std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt;' // requested for (TestMessage::TestItr itr = tmessage.m_testVector.begin(); itr != tmessage.m_testVector.end(); ++itr) { asciiMessage &lt;&lt; *itr; } #endif #if WILL_WORK // This will work for(TestMessage::TestSize index = 0; index &lt; tmessage.m_testVector.size(); ++index) { asciiMessage &lt;&lt; tmessage.m_testVector[index] &lt;&lt; ","; } #endif asciiMessage &lt;&lt; std::endl; std::cout &lt;&lt; asciiMessage.str(); } int main() { TestMessage message; message.m_testVector.push_back(10); message.m_testVector.push_back(20); message.m_testVector.push_back(30); message.m_testVector.push_back(40); printMessage(message); return 0; } </code></pre>
    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. 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