以下幻灯片来自 Bjarne Stroustrups 的演讲“C++ 的本质”:
我是否通过以下简单示例(值、原始指针、资源成员/子对象的智能指针)理解了他的技术?:
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"));
}
};
为什么 1. 优于 2.?如果我实例化一个 foo 对象并取消引用它以获取小 n 成员的值,那么 vector 成员也将被加载到内存中,对吗?有了2,只有指针被加载到内存中!对于这个问题,我想假设 vector 在执行期间会有些大。
此外,为什么 2 (RAII) 优于智能指针?开销不是很相似吗(都在生命周期后销毁资源)?
最佳答案
无论 2 是什么,它都不比任何东西更可取。当您复制一个 foo
对象时,这是一个等待发生的意外。
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!
这很令人困惑——这里的所有内容都已经在内存中了,那么你到底要加载到内存中的是什么?确实2中的foo
比1中的foo
小,所以你可以在同一个cache line中放更多的foo
,当您在不接触 vector
的情况下对 foo
数组进行操作时,可能会产生更好的性能。
但是 vector
本身只不过是三个指针(用于开始、结束、容量),所以它并不是一个巨大的位置损失。 vector
的内容可以任意大(当然有一个限制),但它们在其他地方。当您实际需要使用 vector
时,foo
的较小尺寸带来的微小位置增益很可能会被额外的间接级别消除。
关于c++ - 是什么激发了 Stroustrup 对资源管理技术的偏好顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29179809/