June 03, 2017 Re: How to Compare 2 objects of the same class | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mark | On 06/03/2017 03:38 PM, Mark wrote: > Ok. So by using '==' it should compare the addresses of the objects? That's the default behavior. You can change it with opEquals: http://ddili.org/ders/d.en/object.html#ix_object.opEquals I think you want to use the 'is' operator: http://ddili.org/ders/d.en/class.html#ix_class.is,%20operator It's better because 'is' can be used with null variables. > about 45 lines, that might be a lot of code > for a post. Yeah. Minimal is good. :) > how Can I obtain the actual memory address of a class? You mean the memory address of a class object. ;) It's achieved with the special semantics of casting the class variable to void*: class C { int i; } void info(C o) { import std.stdio; writefln(" Object at %s,\n" ~ "i member at %s\n", cast(void*)o, &o.i); } void main() { auto a = new C(); auto b = new C(); a.info(); b.info(); } Sample output on my system: Object at 7F810AA53060, i member at 7F810AA53070 Object at 7F810AA53080, i member at 7F810AA53090 The difference of 16 bytes are from vtbl pointer and the monitor. (I think the latter is a kind of a lizard, which nobody actually uses. :p) Ali |
June 03, 2017 Re: How to Compare 2 objects of the same class | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Saturday, 3 June 2017 at 23:32:44 UTC, Ali Çehreli wrote:
...
> Ali
Awesome, that might be handy in the near future.
Thanks.
|
June 03, 2017 Re: How to Compare 2 objects of the same class | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mark | On Sat, Jun 03, 2017 at 10:38:31PM +0000, Mark via Digitalmars-d-learn wrote: [...] > Ok. So by using '==' it should compare the addresses of the objects? [...] No, `==` is for comparing the *contents* of the objects. You need to implement opEquals() for the objects being compared in order to define how the contents will be compared. If you want to compare *addresses*, use `is`: Object a = new Object(...); Object b = a; // b is a reference to the same object as a assert(b is a); In this case there is no need to implement anything else, since comparing addresses is simple. T -- "No, John. I want formats that are actually useful, rather than over-featured megaliths that address all questions by piling on ridiculous internal links in forms which are hideously over-complex." -- Simon St. Laurent on xml-dev |
Copyright © 1999-2021 by the D Language Foundation