Re: delete the dynamically allocated memory twice causes error
Junhui Tong wrote:
:: BobR wrote:
:: [snip]
::: #include <iostream>
::: #include <vector>
::: int main(){
::: std::vector<int> pi( 1, 12 );
::: // Tong "Another example is that C++ also won't check whether
::: // an array index is out of bound."
::: // And what does '.at()' do?
:: but vector is not the built-in `array'.
::: std::cout << pi.at(0);
::: return 0;
::: }
:::
::: Much 'easier'! How much 'efficiency' did that give up?
:: Yes, `at' lose efficiency, here is a typical implementation of
:: vector<>::at: const_reference at(size_type _Pos) const
:: {
:: if (size() <= _Pos) // waste an extra compare here
:: _Xran();
:: return (*(begin() + _Pos));
:: }
::
We might be losing very little efficiency for an added check. The
compiler I use, will recognize that in the code
for (std::size_t i = 0; i < v.size(), ++i)
cout << v.at(i);
the two tests "i < v.size()" and "size() <= _Pos" both compare the
loop-variable against size(). So it will merge the code into the loop
termination test, resulting in "size() <= _Pos" in effect being
evaluated only once, before the loop!
An extremely small price performance-wise!
Bo Persson