effictive c item14中的疑问

时间:2008-05-10 05:02:46   来源:论坛整理  作者:  编辑:chinaitzhe
item 14有如下描述:
Copy the underlying resource. Sometimes you can have as many copies of a resource as you like, and the only reason you need a resource-managing class is to make sure that each copy is released when you're done with it. In that case, copying the resource-managing object should also copy the resource it wraps. That is, copying a resource-managing object performs a "deep copy."

Some implementations of the standard string type consist of pointers to heap memory, where the characters making up the string are stored. Objects of such strings contain a pointer to the heap memory. When a string object is copied, a copy is made of both the pointer and the memory it points to. Such strings exhibit deep copying.
其中
copying the resource-managing object should also copy the resource it wraps.复制资源治理的对象是,应该同时复制其所指向的对象。结合紧接着的那个string的例子,复制string object时,应该复制指针和指针所指的对象。
我的问题是这样的,既然要同时复制指针所指的对象,不就是相当于重新构造出了此类的另外一个对象了么?那std::tr1::shared_ptr所指的岂不总是一个对象,那和std::auto_ptr还有什么区别啊?
请问这个item的这个部分该怎么去理解?

网友回复:我的问题是这样的,既然要同时复制指针所指的对象,不就是相当于重新构造出了此类的另外一个对象了么?
并不一定,只要以前的指针放弃拥有权,把拥有权给现在的指针就OK了.

那std::tr1::shared_ptr所指的岂不总是一个对象,那和std::auto_ptr还有什么区别啊?
前者没有看过,后者就是做到在复制构造,赋值的时候新对象拥有控制权,原有的放弃

这个item的意思是说在设计的时候要注重其复制的行为.
网友回复:我还是没理解,就拿书中的例子来说:
有类:
class Lock {

public:

explicit Lock(Mutex *pm) // init shared_ptr with the Mutex

: mutexPtr(pm, unlock) // to point to and the unlock func

{ // as the deleter


lock(mutexPtr.get()); // see Item 15 for info on "get"

}

private:

std::tr1::shared_ptr <Mutex> mutexPtr; // use shared_ptr

};
当进行如下操作的时候:
Lock ml1(&m);
Lock ml2(ml1);
我理解的是应该ml1中的mutexPtr与ml2中的mutexPtr所指的是同一块内存。
但是这和下面的有些矛盾啊,假如进行深层复制,那就是ml2也开辟了一块新内存,只不过储存的和ml1储存的value是一样的,是这样么?


网友回复:顶下
网友回复:应该是指向同一内存,另外这个智能指针好象应该还有个内部记数器,当记数器值为0时才销毁该内存,大于0时不销毁。
不知理解的对不对。
网友回复:你看的是第几版?第二版还是第三版?
网友回复:shared_ptr,应该是第三版。
网友回复:shared_ptr是就更前面"Reference-count"那段而给的例子;你的引文则是Copy the underlying resource,已经是另一段了。所以这一段和shared_ptr扯不上关系。
关键字:effictive,item,疑问,

文章评论

共有 0 位网友发表了评论 此处只显示部分留言 点击查看完整评论页面