digitalmars.D.learn - Structs and Classes
- Mars (10/10) Jan 31 2012 Hello everybody.
- Mike Parker (7/17) Jan 31 2012 Structs are value types, so when you return one from a function or pass
Hello everybody. I couldn't really think of a good title for this. It's just a little question, about this example code: http://pastie.org/private/4xqtze47dlx9fy9pn53sq Apperantly I get a copy of Bar, when I call bar(), and it doesn't modify the actual variable of the object. But if I define Bar as a class, it works as expected (by silly me). Why is that? And if I want to use a struct for this, is the passing around of a pointer (like in the example) correct? Mars
Jan 31 2012
On 1/31/2012 7:45 PM, Mars wrote:Hello everybody. I couldn't really think of a good title for this. It's just a little question, about this example code: http://pastie.org/private/4xqtze47dlx9fy9pn53sq Apperantly I get a copy of Bar, when I call bar(), and it doesn't modify the actual variable of the object. But if I define Bar as a class, it works as expected (by silly me). Why is that? And if I want to use a struct for this, is the passing around of a pointer (like in the example) correct? MarsStructs are value types, so when you return one from a function or pass as a function argument, it's actually a copy that gets handed around. Classes are reference types, so when you move those around it's very much like using a pointer. To get reference semantics on a struct, you have either use it as a pointer or use the ref keyword to create a reference.
Jan 31 2012