C++: converting a container to a container of different yet compatible type

后端 未结 8 1015
南笙
南笙 2021-01-05 08:28

It often happens to me to have a a container C (or whatever kind of wrapper class, even smart pointers) for a type T1, and want to convert such

8条回答
  •  没有蜡笔的小新
    2021-01-05 08:56

    Why not use the safe way

    C c1;
    /* Fill c1 */
    C c2(c1.begin(), c1.end());
    

    and then profile. If it turns out to be a bottleneck then you can always revisit your underlying algorithm and perhaps remove the need for a conversion completely.

    Relying on any particular behavior from reinterpret_cast may not cause problems now but months or years from now it will almost certainly cause someone debugging problems.

提交回复
热议问题