The following slide is from Bjarne Stroustrups talk "The Essence of C++":
Do I understand his techniques with the following simple examples (values, raw pointers, smart pointer for resource members/subobjects)?:
1.
class foo{
std::vector<bar> subObj;
int n;
public:
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 is 1. preferable over 2.? If I instantiate a foo object and dereference it in order to get the value of the small n member, the vector member will be loaded into memory as well, right? With 2, only the pointer is loaded into memory! For this question I want to assume that the vector will be somewhat large during execution.
Also, why is 2 (RAII) preferable over smart pointers? Isn't the overhead pretty similar (both destruct the resource after the lifetime)?