What does const struct
mean? Is it different from struct
?
You can const individual members of a struct. Declaring an entire instance of a struct with a const qualifier is the same as creating a special-purpose copy of the struct with all members specified as const .
A C# struct is managed code, which will be freed by the C# garbage when nobody refers to it anymore. Its destructor is called whenever the garbage collector decides to clean it up. A C++ struct is an unmanaged object, which you have to clean up yourself.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
Can C++ struct have member functions? Yes, they can.
The const
part really applies to the variable, not the structure itself.
e.g. @Andreas correctly says:
const struct { int x; int y; } foo = {10, 20}; foo.x = 5; //Error
But the important thing is that variable foo
is constant, not the struct
definition itself. You could equally write that as:
struct apoint { int x; int y; }; const struct apoint foo = {10, 20}; foo.x = 5; // Error struct apoint bar = {10, 20}; bar.x = 5; // Okay
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With