这取决于具体情况,在内存空间至关重要的某些情况下,创建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);