c++ - How is returning an object by reference possible? -


i reading opencv tutorial , said following opencv's image holder class (cv::mat):

the cv::mat class implements reference counting , shallow copy such when image  assigned one, image data (that pixels) not copied, , both images  point same memory block. applies images passed value or returned  value. reference count kept such memory released when of  references image destructed.  

i'm specficially interested in part says this applies images passed value or returned. how possible point same memory block when passed value? feel overloading = operator. says if image returned, returns image points same memory block , doesn't create new one. don't understand how implemented this.

but here's understand:

given pass value , returning image make new image share same memory block, makes sense implement reference counting.

but explain how memory block shared, when object returned or passed value?

this relatively easy: in class' constructor, allocate memory, e.g. using new. if make copy of object, don't allocate new memory every time, rather copy pointer original block of memory, while incrementing reference counter stored in memory somewhere such each copy of object has access it. destroying object decrement reference count , free allocated memory if reference count drops zero.

a custom copy constructor , assignment operator need this.

this how shared pointers work.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -