c++ - What motivates Stroustrup's order of preference for resource management techniques? -


the following slide bjarne stroustrups talk "the essence of c++":

enter image description here

do understand techniques following simple examples (values, raw pointers, smart pointer resource members/subobjects)?:
1.

class foo{       std::vector<bar> subobj;       int n;   pubic:       foo(int n) : n(n) {         subobj.push_back(bar("snickers"));     }  }; 

2.

class foo{       std::vector<bar>* subobj;       int n;   public:     foo(int n) : n(n){         subobj = new std::vector<bar>();         subobj->push_back(bar("snickers"));     }       ~foo() {         delete subobj;     } }; 

3.

class foo{         std::unique_ptr<std::vector<bar> > subobj;       int n;   public:        foo(int n) : n(n){           subobj(new std::vector<bar>());           subobj->push_back(bar("snickers"));       } };  

why 1. preferable on 2.? if instantiate foo object , dereference in order value of small n member, vector member loaded memory well, right? 2, pointer loaded memory! question want assume vector large during execution.

also, why 2 (raii) preferable on smart pointers? isn't overhead pretty similar (both destruct resource after lifetime)?

whatever 2 is, it's not preferable on anything. accident waiting happen make copy of foo object.

why 1. preferable on 2.? if instantiate foo object , dereference in order value of small n member, vector member loaded memory well, right? 2, pointer loaded memory!

this pretty confused - here in memory loading memory? true foo in 2 smaller foo in 1, can fit more foos in same cache line, potentially yielding better performance when operate on array of foos without touching vector.

but vector little more 3 pointers (for begin, end, capacity), it's not if it's huge locality loss. contents of vector can arbitrarily large (up limit, of course) elsewhere. , tiny locality gain smaller size of foo in likelihood erased level of indirection whenever need use vector.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -