我对下面的案例有点困惑。我有以下 C++ 类,代表一个 RGB 像素:
class RgbColorVector
{
cv::Mat pM;
public:
RgbColorVector(unsigned int r,unsigned int g,unsigned int b)
{
pM = cv::Mat(3,1,CV_8UC1);
pM.at<unsigned char>(0,0) = r;
pM.at<unsigned char>(1,0) = g;
pM.at<unsigned char>(2,0) = b;
}
unsigned int getComponent(int c)
{
return (unsigned int)pM.at<unsigned char>(c,0);
}
这里我使用 OpenCV Mat 对象来保存 RGB 值。通常在这种情况下,我会使用 cv::Mat 指针并在构造函数中使用 new 运算符分配堆内存,然后在析构函数中使用 delete 释放它。在上面的例子中,我显式地调用了 cv::Mat 的构造函数。我期望的是,当 RgbColorVector 的构造函数退出时, cv::Mat 构造函数中分配的内存将被销毁。但显然不是这样的:
void func()
{
RgbColorVector rgbVec(105,42,45);
int g = rgbVec.getComponent(1);
std::cout<<g<<std::endl;
}
int main(int argc, const char * argv[]) {
func();
return 0;
}
在这里,我得到输出 42。我知道“rgbVec”是一个本地(自动)变量,当“func”退出时,它的内容(类成员)将被销毁。但此外,我预计 getComponent() 调用将返回一个随机值,因为在 cv::Mat 构造函数调用中分配的任何内存都将在“rgbVec”的构造函数返回后被销毁。我在这里有点困惑,在这种情况下内存分配机制究竟是如何工作的? RgbColorVector() 构造函数中的 cv::Mat 对象不是分配在堆栈上吗?
最佳答案
class RgbColorVector
{
cv::Mat pM; // <- this object is valid as long
// as the parent is (value semantics)
public:
RgbColorVector(unsigned int r,unsigned int g,unsigned int b)
// <- pM gets implicitly allocated here
{
pM = cv::Mat(3,1,CV_8UC1); // <- this creates a temporary, and
// assign its value to pM
// <- the temporary gets implicitly deallocated here.
// pM isn't affected.
pM.at<unsigned char>(0,0) = r;
pM.at<unsigned char>(1,0) = g;
pM.at<unsigned char>(2,0) = b;
}
};
初始化成员的正确方法是这样的:
RgbColorVector(unsigned int r,unsigned int g,unsigned int b)
: pM(3,1,CV_8UC1)
{
这称为成员初始化列表
关于c++ - C++类: Where should it be destroyed?的成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42313630/