c++ - Why access from child class to the field of other exemplar of superclass crashed this field? -
Within the second amplifier class, when the value of the method clone (s) is changing the value value field.
Listing:
Includes # lt; Iostream & gt; using namespace std; Square set {public: set (integer minute, maximum maximum) {num_bits = max-min + 1; NUM_BYTES = (num_bits + 7) / 8; Elems = new int8_t [num_bytes]; For (int i = 0; i & lt; num_bytes; i ++) ames [i] = 0; MinElem = minutes; MaxElem = Max; }; Zero plus (int n) {int bit = n-minElem; Elems [bit / 8] | = (1 & lt; <(bit% 8)); }; Zero del (int n) {int bit = n-minElem; Elems [bit / 8] & amp; = ~ (1 <-bitt% 8)); }; Bool is (int n) {int bit = n-minElem; Return (elems [bit / 8] & amp; (1 & lt; & lt; (bit% 8))); } Zero print () // str {int i = 0; Do {cout & lt; & Lt; (Is (i + minElem)? "1": "0"); I ++; If (i% 8 == 0) cout & lt; & Lt; ""; } While (i & lt; num_bits); } ~ Set () {delete} ames; }; Public: // rotate int num_bits, num_bytes, minElem, maxElem; Int8_t * Ams; }; Class Excerpt: Public Set {Public: ExSet (int min, int max): set (minimum, maximum) {} ExSet: set (s.minElem, s.maxElem) {/ * clone (s); Zero clone (set s) {// (int i = 0; i & lt; num_bytes; i ++) for {} {int x = s.elems [i]; Cout & lt; & Lt; Elems [i] & lt; & Lt; '=' & Lt; & Lt; S.elems [i] & lt; & Lt; '/';}}; }; Main () {char * p = "ABCZabxyz"; Set ('a', 'z'); Do s.add (* p); While (* ++ p = '\ 0'!); S.del ('b'); S.print (); The court's & lt; & Lt; Endl; For (four C = 'A'; C; l =; z '; c ++) if (SHAS (C)) COAT & LT; & Lt; C; The court's & lt; & Lt; Endl; // Delete & amp; ExSet es (s); For (four C = 'A'; C; l =; z '; c ++) if (SHAS (C)) COAT & LT; & Lt; C; }; Expected: 10100000 00000000 00000000 01000000 11000000 00000000 00000001 11 ACZabxyz ACZabxyz
Go:
10100000 00000000 01000000 11000000 00000000 00000001 11 ACZabxyz FGINQRVWghqrvw
The row is the source of your memory problems.
ExSet: Set (s.minElem, s.maxElem) {/ * clone (s); * /}
When you execute
ExSet es (s); A temporary copy of s
is created by calling the creator of ExSet
in the call. When it is temporarily destroyed, it removes the memory organized by elems
.
When the s
is destroyed, then the same memory is removed again. This is an undefined behavior. In your case, it produces wrong results. In other cases, this program may crash.
You can solve this particular problem by using ExSet (set set & amp;): set (s.minElem, s. However, a reasonable For Fix, provide a copy constructor and a copy assignment operator in set
. To understand, see why.
Comments
Post a Comment