On 08/06/2015 04:58, Stefan Ram wrote:
> Peng Yu <
peng...@gmail.com> writes:
>> Suppose that I have a variable of vector<unsigned>, and a
>> function that takes an argument of const vector<int>&.
>> Is there a way to somehow directly supply the variable to the
>> function without using a copy?
>
> You can cast the object, but this might mean that the cast
> or call will have undefined behaviour or in the best case
> will behave as if each unsigned was reinterpret as an int.
>
> Under some implementations this might be acceptable when all
> the unsigned objects have values that can be represented as
> an int.
>
> For example, one implementation gave:
>
> #include <iostream>
> #include <ostream>
> #include <vector>
> #include <climits>
>
> int main()
> { ::std::vector< unsigned >v{ 0, 1, INT_MAX,( unsigned )INT_MAX +( unsigned )1 };
> for( unsigned u : v )::std::cout << u << '\n';
> auto const &w( *reinterpret_cast< ::std::vector< int >* >( &v ) );
> for( int i : w )::std::cout << i << '\n'; }
>
> 0
> 1
>
2147483647
>
2147483648
> 0
> 1
>
2147483647
> -
2147483648
You know it is UB yet you still suggest it? It is never acceptable to
deliberately invoke UB. Mate, I am sorry but if you wrote such code for
me you would be fired.
/Flibble