In C++, I have seen 2 ways to create a new struct:
1.
StructA a;
a.member1 = ...;
foo(&a); // void foo(StructA* a);
2.
StructA* a = new StructA;
a->member1 = ...;
foo(a);
What are the difference and implications of these 2 code snipets?
Thanks
In C++, I have seen 2 ways to create a new struct:
1.
StructA a;
a.member1 = ...;
foo(&a); // void foo(StructA* a);
2.
StructA* a = new StructA;
a->member1 = ...;
foo(a);
What are the difference and implications of these 2 code snipets?
Thanks
The difference in a nutshell:
StructA a declares a variable that is a StructA.
StructA* a declares a pointer that points to a StructA.
The implications:
The variable StructA is can be immediately used to store data.
The pointer StructA* must be set to point to an actual struct before it can be used to store data.
The variable StructA will automatically be deallocated when the current block exits.
While the pointer StructA* will be deallocated when the current block exits, the data it is pointing to (created with new) will not go away until delete is called. If delete is never called, then your program will have a memory leak.