返回从函数内的新结构创建的结构 [英] Return struct created from new struct within function

查看:66
本文介绍了返回从函数内的新结构创建的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,从函数返回的结构体中的数组指针是否指向用新结构体定义的同一个内存块?

In this code, does the array pointer in the struct returned from the function point to the same block of memory that was defined with the new struct?

#include <iostream>
#include <math.h>

struct Arr
{
    const int Col;
    const int Row;
    double* CAR{ new double[Col * Row] };
    Arr(int y, int x) : Col(x), Row(y) {}
    void Del() { delete[] CAR; }
    int Indx(int y, int x) { return (x + y * Col); }
    int Size() { return Col * Row; }
    void Print(std::string title);
};
void Arr::Print(std::string title)
{
    std::cout << title << '\n';
    for (int I = 0; I < Row; I++)
    {
        for (int In = 0; In < Col; In++)
        {
            std::cout << CAR[Indx(I, In)] << " / ";
        }
        std::cout << '\n';
    }
}
const Arr retfunc(std::string h, Arr& a, Arr& b)
{
    Arr* temp = NULL;
    if (h == "Had") 
    {
        temp = new Arr(a.Row, a.Col);
        for (int I = 0; I < a.Row; I++)
        {
            for (int In = 0; In < a.Col; In++)
            {
                temp->CAR[temp->Indx(I, In)] = a.CAR[a.Indx(I, In)] * b.CAR[b.Indx(I, In)];
            }
        }
    } Arr T = *temp; return T;
}

int main()
{
    int val = 5;
    Arr a(2, 2);
    Arr b(2, 2);
    for (int I = 0; I < 2; I++)
    {
        for (int In = 0; In < 2; In++)
        {
            a.CAR[a.Indx(I, In)] = 10.0 / val + In;
            b.CAR[b.Indx(I, In)] = 8.0 / val + In;
        }
    }
    a.Print("a");
    b.Print("b");
    Arr S = retfunc("Had", a, b);
    S.Print("S");   
    S.Del();
}

那么本质上,在 S 上调用 delete 会清除在 retfunc 中分配的相同内存吗?

So essentially then, does calling delete on S clear the same memory that was allocated in retfunc?

推荐答案

对于初学者来说,函数 retfunc 存在内存泄漏,因为函数内动态分配的对象 temp 是没有被释放.

For starters the function retfunc has a memory leak because the object temp dynamically allocated within the function is not freed.

由于该类没有显式复制构造函数,因此在此声明中

As the class does not have an explicit copy constructor then in this declaration

Arr T = *temp

使用了按成员方式将对象 temp 的数据成员复制到对象 T.对象 temp 的指针 CAR 的值将被复制到对象 T 的指针 CAR 中,并且将是一个有效的指针到动态分配的对象 temp 的生命周期.

there is used member-wise copying of data members of the object temp to the object T. The value of the pointer CAR of the object temp will be copied in the pointer CAR of the object T and will be a valid pointer due to the life-time of the dynamically allocated object temp.

当在类中动态分配内存时,您需要编写显式析构函数、左值和右值的复制构造函数以及左值和右值的复制赋值运算符.

When within a class there is dynamically allocated memory then you need to write an explicit destructor, copy constructors for lvalues and rvalues and copy assignment operators for lvalues and rvalues.

这篇关于返回从函数内的新结构创建的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆