如果使用引用传递对象,则会增加引用计数类中的引用计数

should passing an object using its reference increase the reference count in a reference counting class

本文关键字:引用 增加 如果 对象      更新时间:2023-10-16

我正在编写一个使用引用计数来管理其资源的类。

如果类使用其引用传递给函数,是否应该添加引用?

如果我的对象通过它的引用传递给一个函数,我会在调用的类上获得一个复制构造函数或任何其他方法吗?

例如,我想知道它是如何在share_pointer或cv::Mat中实现的。

如果我将cv::Mat传递到使用引用的方法中,是否添加了它们的引用计数器?

例如:

void func(cv::Mat & image)
{
     // what is the reference counter here? is it one or two?
}
main()
{
     cv::Mat image;
     // reference counter for image should be one here.
     funct(image);
 }

引用计数通常在复制构造函数、赋值运算符和析构函数中跟踪。如果通过引用传递,那么这些函数都不会被调用,因此引用计数将保持不变。

void func(cv::Mat image) //reference count increased due to copy
{
} //reference count decreased due to destruction
void func(cv::Mat& image) //no copy, reference count unchanged
{
} //no destructor call, reference count unchanged

通常,当一个类有引用计数时,它会存储该对象的副本数量。通过引用传递对象时,不会进行复制。编译器可能正在使用指针,也可能正在使用实际对象,但它没有进行复制,因此引用计数器不会增加。