【问题标题】:Accessing members of structs using dot or arrow notation使用点或箭头符号访问结构的成员
【发布时间】:2022-09-27 18:22:34
【问题描述】:

我想知道使用符号mystruct.element1 而不是mystruct->element1 访问结构的优点和缺点是什么。

或者更确切地说,将结构定义为指针是好是坏,即

structtype * mystruct; or structtype mystruct; 

在我的代码中,我希望将各种结构作为输入传递给某些函数,目前我将它们作为引用传递,如下所示:

void myfunc(structtype &mystruct, double a[]) 
{
     a[0] = mystruct.element0;
}

结构将像往常一样定义的地方(我认为)

struct structtype{
    double element0;
};
structtype mystruct;

    标签: c++ pointers struct reference member


    【解决方案1】:

    这取决于具体情况,在内存空间至关重要的某些情况下,创建structtype 类型的指针会很好。

    例如在下一个代码中:

    #include <iostream>
    using namespace std;
    
    struct structtype {
        double element0;
        int element1;
        int element2;
    };
    
    structtype mystruct;
    
    void func(structtype &s)
    {
        cout << "size of reference pointer : "  << sizeof(&s);
    }
    
    int main() {
        cout <<"size of object : " << sizeof(mystruct) << endl;
        func(mystruct);
        return 0;
    }
    

    这是输出:

    size of object : 16
    size of reference pointer : 4
    

    注意指针占用的大小只有 4 个字节而不是 16 个字节。因此,当您想节省空间时,指针会派上用场,而不是创建多个对象,每个对象的大小为 16 字节,这将消耗内存,您可以只创建一个对象并进行任何函数调用,只需引用该对象的地址所以你可以节省一些内存。

    同样在其他情况下,您将需要您的对象不要像以下代码一样被破坏:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    typedef struct structtype {
        double element0;
        int element1;
        int element2;
    }structtype;
    
    structtype* func()
    {
        structtype s1;
        s1.element1 = 1;
        return &s1;
    }
    
    int main() {
        structtype *sRet = func();
        structtype s2 = {1546545, 5, 10};
        printf("element1 : %d", sRet->element1);
        return 0;
    }
    

    上面的代码是未定义的行为,并且会通过一些奇怪的输出,因为 structtype s1; 被声明为对象而不是指向堆中对象的指针,所以在调用 func 的函数结束时,它将被破坏并且不在堆栈中,而在指针的情况下,您可以创建一个指向堆中对象的指针,除非您明确指定,否则该对象不能被销毁,因此指针在这一点上也派上用场。您可以创建一个指向堆中对象的指针C++像这样:

    structtype *s1 = new structtype;
    

    为了释放那段记忆,你必须输入C++:

    delete(s1);
    

    【讨论】:

      猜你喜欢
      • 2013-02-02
      • 2011-06-26
      • 2022-01-18
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多