Can I call `delete` on a vector of pointers in C++ via for_each ?

后端 未结 7 1537
醉梦人生
醉梦人生 2021-01-14 08:32

Suppose I have a std::vector objs (for performance reasons I have pointers not actual Objs).

I populate it with obj.push

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 09:06

    While you can do this (GMan has shown a solution), having containers with naked pointers to owned resources is a strong code smell. For example, in this code:

      void foo()
      {
        std::vector bar;
        fill(bar);
        use(bar);
        std::for_each(objs.begin(), objs.end(), delete_ptr()); // as GMan suggests
      }
    

    if use() throws, you'll leak objects.

    So it's better to use smart pointers for this:

    std::vector< std::shared_ptr > bar;
    

提交回复
热议问题