File: SmartPtr.h

package info (click to toggle)
ntl 11.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,820 kB
  • sloc: cpp: 92,194; sh: 10,577; ansic: 3,058; makefile: 536
file content (2049 lines) | stat: -rw-r--r-- 47,241 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049


#ifndef NTL_SmartPtr__H
#define NTL_SmartPtr__H

#include <NTL/tools.h>
#include <NTL/thread.h>

// NOTE: <NTL/tools.h> includes <utility>, which provides std::forward



NTL_OPEN_NNS



/****************************************************************************

SmartPtr: a smart pointer class.

Synopsis: provides a reference counted smart pointer, similar to shared_ptr
in the standard library.  It is provided here to minimize reliance
on the standard library, especially for older C++ compilers, which may
not provide shared_ptr, or it may be in TR1, which gets messy.


Examples:


  SmartPtr<T> p1;         // initialize to null
  SmartPtr<T> p1(0);
  SmartPtr<T> p1 = 0;

  SmartPtr<T> p2(p1);     // copy constructor

  T *rp;
  SmartPtr<T> p2(rp);     // construct using raw pointer (explicit): better 
                          // to use MakeSmart below

  p1 = MakeSmart<T>(...); // build new T object by invoking constructor
                          // T(...) with pseudo-variadic templates.
                          // This is safer and more efficient that
                          // using the raw-pointer constructor
                        
  p1 = p2;                // assignment
  p1 = 0;                 // assign null


  if (!p1) ...            //  test for null
  if (p1 == 0) ... 

  if (p1) ...             // test for not null ... 
  if (p1 != 0) ... 

  if (p1 == p2) ...       // test for equality 
  if (p1 != p2) 

  *p1                     // dereferencing
  p1->...

  p1.get();               // return the underlying raw pointer...dangerous!

  p1.swap(p2);            // fast swap
  swap(p1, p2);


Automatic Conversions:

If S is another class, SmartPtr<S> converts to SmartPtr<T> if S* converts to T*
(for example, if S is a subclass of T).  Similarly, SmartPtr<S> and SmartPtr<T>
may be compared if S* and T* may be compared.

MakeSmart:

One can write SmartPtr<T> p = MakeSmart<T>(x1, ..., xn), and this will create a
smart pointer to an object constructed as T(x1, ..., xn).  Besides notational
convenience, it also reduces the number of memory allocations from 2 to 1, as
the data and control block can be allocated in one chunck of memory.

This is implemented without reliance on C++11 features, which means that there
are limitations.  First, the number n of arguments is limited to 9.  And
second, all arguments are pass by const reference. However, you can work around
this by using the helper function Fwd.  For example, if T has a 2-argument
constructor where the second must be a non-const reference of some type, and x2
is a variable of that type, you can write MakeSmart<T>(x1, Fwd(x2)), to forward
that reference through all the template nonsense in a typesafe manner.

MakeRaw:

One can also write T *p = MakeRaw<T>(x1, ..., xn) to create a 
raw pointer.  This is the same as writing T *p = new T(x1, ..., xn),
except that if the construction fails, NTL's error routine will be called
(as opposed to an exception being thrown).  The same restrictions and
limitations that apply to MakeSmart appy to MakeRaw.

MakeRawArray:

Another utility routine: one can write T *p = MakeRawArray<T>(n)
to make a plain array of n T's.  NTL's error routine will be
called if the allocation fails.

Dynamic casting:

I've also supplied a dynamic cast operation for smart pointers.

   SmartPtr<Derived> d = MakeSmart<Derived>(); // d points to Derived
   SmartPtr<Base> b = d; // implicit upcast: OK

   SmartPtr<Derived> d1 = DynamicCast<Derived>(b);
      // downcast to a Derived object -- returns null for a bad cast
   



Implementation notes:

If NTL is compiled with the NTL_THREADS option, then the reference counting
should be thread safe.

The SmartPtrControl class heirarchy is used to make sure the right destructor
is called when the ref count goes to zero.  This can be an issue for forward
declared classes and for subclasses.  For example, if T is forward declared in
a context where the ref count goes to zero, or if the object's actual type is a
subclass of T and T's destructor was not declared virtual.

The null tests p, !p, p == 0, are all affected via an implicit conversion from
SmartPtr<T> to a funny pointer type (a pointer to a member function, which
avoids other, unwanted implicit conversions: this is the so-called "safe bool
idiom");

There is also an assigmment from a funny pointer type to a SmartPtr,
which asslows assigment of 0 to a SmartPtr.

In C++11 both of the above effects could perhaps be achieved more directly.
The new "explict bool" operator can replace the "safe bool idiom", and I would
think that the new null pointer type could be used to get the assignment of 0
to work.

NOTES: See http://www.artima.com/cppsource/safebool.html for more
on the "safe bool idiom".  

 


*****************************************************************************/

// Helper class for somewhat finer-grained control of deleter.
// Useful in the PIMPL pattern.

struct DefaultDeleterPolicy {

   template<class T>
   static void deleter(T *p) { delete p; }

};

// A tagging class, for better readability

template<class P>
struct ChoosePolicy { };

// usage: SmartPtr<T> p(r, ChoosePolicy<MyDeleterPolicy>());



class SmartPtrControl {
public:
   AtomicRefCount cnt;
   SmartPtrControl() { }
   virtual ~SmartPtrControl() { }


private:
   void operator=(const SmartPtrControl&); // =delete
   SmartPtrControl(const SmartPtrControl&); // =delete
};



template<class T, class P=DefaultDeleterPolicy>
class SmartPtrControlDerived : public SmartPtrControl {
public:
   T* p;

   SmartPtrControlDerived(T* _p) : p(_p)  { }

   ~SmartPtrControlDerived() 
   { 
      P::deleter(p);
   }

};

 
struct SmartPtrLoopHole { };


template<class T>
class SmartPtr {
private:
   T *dp;
   SmartPtrControl *cp;

   void AddRef() const
   {
      if (cp) cp->cnt.inc();
   }

   void RemoveRef() const
   {
      if (cp && cp->cnt.dec()) { delete cp; }
   }

   class Dummy { };
   typedef void (SmartPtr::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (SmartPtr::*fake_null_type1)(Dummy1) const;


public:
   long get_count() const { return cp ? cp->cnt.get_count() : 0; }
   // mainly for debugging

   template<class Y>
   explicit SmartPtr(Y* p) : dp(p), cp(0) 
   {
      if (p) {
         cp = NTL_NEW_OP SmartPtrControlDerived<Y>(p);
         if (!cp) {
            delete p;  // this could theoretically throw an exception
            MemoryError();
         }
         AddRef();
      }
   }

   template<class Y, class P>
   SmartPtr(Y* p, ChoosePolicy<P>) : dp(p), cp(0) 
   {
      if (p) {
         cp = NTL_NEW_OP SmartPtrControlDerived<Y,P>(p);
         if (!cp) {
            delete p;  // this could theoretically throw an exception
            MemoryError();
         }
         AddRef();
      }
   }

   SmartPtr() : dp(0), cp(0)  { }

   SmartPtr(fake_null_type1) : dp(0), cp(0) { }

   SmartPtr(SmartPtrLoopHole, T* _dp, SmartPtrControl *_cp) : dp(_dp), cp(_cp)
   { 
      AddRef();
   } 

   ~SmartPtr() {
      RemoveRef();
   }

   SmartPtr(const SmartPtr& other) : dp(other.dp), cp(other.cp) 
   {
      AddRef();
   }

   SmartPtr& operator=(const SmartPtr& other)
   {
      SmartPtr tmp(other);
      tmp.swap(*this);
      return *this;
   }

   template<class Y> friend class SmartPtr;

   template<class Y>
   SmartPtr(const SmartPtr<Y>& other) : dp(other.dp), cp(other.cp) 
   {
      AddRef();
   }


   template<class Y>
   SmartPtr& operator=(const SmartPtr<Y>& other)
   {
      SmartPtr tmp(other);
      tmp.swap(*this);
      return *this;
   }

#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   SmartPtr(SmartPtr&& other) noexcept : dp(other.dp), cp(other.cp) 
   {
      other.dp = 0;
      other.cp = 0;
   }

   SmartPtr& operator=(SmartPtr&& other) noexcept
   {
      SmartPtr tmp(std::move(other));
      tmp.swap(*this);
      return *this;
   }

   template<class Y>
   SmartPtr(SmartPtr<Y>&& other) noexcept : dp(other.dp), cp(other.cp) 
   {
      other.dp = 0;
      other.cp = 0;
   }


   template<class Y>
   SmartPtr& operator=(SmartPtr<Y>&& other) noexcept
   {
      SmartPtr tmp(std::move(other));
      tmp.swap(*this);
      return *this;
   }

#endif



   T& operator*()  const { return *dp; }
   T* operator->() const { return dp; }

   T* get() const { return dp; }

   void swap(SmartPtr& other)
   {
      _ntl_swap(dp, other.dp);
      _ntl_swap(cp, other.cp);
   }


   operator fake_null_type() const 
   {
      return dp ?  &SmartPtr::fake_null_function : 0;
   }


   template<class Y> 
   SmartPtr<Y> DynamicCast() const 
   {
      if (!dp) 
         return SmartPtr<Y>();
      else {
         Y* dp1 = dynamic_cast<Y *>(dp);
         if (!dp1) return SmartPtr<Y>();
         return SmartPtr<Y>(SmartPtrLoopHole(), dp1, cp);
      }
   }


};


template <class T> NTL_DECLARE_RELOCATABLE((SmartPtr<T>*))


// free swap function
template<class T>
void swap(SmartPtr<T>& p, SmartPtr<T>& q) { p.swap(q); }

// free dynamic cast function
template<class X, class Y>
SmartPtr<X> DynamicCast(const SmartPtr<Y>& p)  { return p.template DynamicCast<X>(); }



// Equality testing

template<class X, class Y>
bool operator==(const SmartPtr<X>& a, const SmartPtr<Y>& b)
{
   return a.get() == b.get();
}

template<class X, class Y>
bool operator!=(const SmartPtr<X>& a, const SmartPtr<Y>& b)
{
   return a.get() != b.get();
}


/*********************************************************************************

Experimantal: CloneablePtr<T> ...essentially same interface as SmartPtr, but 
allows cloning of complete objects.  The differences:
*  must construct using MakeCloneable
*  a clone method is provided
*  implicit conversion from CloneablePtr to SmartPtr is allowed

Example:

   CloneablePtr<Derived> d = MakeCloneable<Derived>(); // d points to Derived
   CloneablePtr<Base> b = d; // implicit upcast: OK

   CloneablePtr<Base> b1 = b.clone(); // clone of b, which is really a Derived object
   CloneablePtr<Derived> d1 = DynamicCast<Derived>(b1);
      // downcast to a Derived object -- returns null for a bad cast
   SmartPtr<Base> b2 = d1;
   


Implementation:

In the clone method, the object is constructed using the copy constructor for the 
type T, where T is the compile-time type with which the first smart pointer to this
object was was created, even if the pointer has been subsequently upcasted to a
base type S.  Such objects must have been initially created using the
MakeCloneable function.  It turns out, this is hard to do in a completely
standards-compliant way, because of the type erasure going on.  The only way I
could figure out how to do it in a standards-compliant way was by using
exceptions: the control block throws a T* and the smart pointer doing the clone
catches an S*.  However, this turned out to be dreadfully slow, and even this
does not completely solve the problem, because there could be ambiguities
in this type of upcasting that miay arise with multiple inheritance.  So I settled
on the current method, which does some low-level pointer arithmetic.  Even with
fancy things like multiple and virtual inheritance, it should work, under the
assumption that if two objects have the same (runtime) type, then their memory
layout is the same.  I don't think anything like that is guaranteed by the
standard, but this seems reasonable, and it seems to work.
Like I said, it is experimental, and I would appreciate feedback
from C++ gurus.

Note that NTL does not use this feature, but I do have applications where this
is convenient.


**********************************************************************************/

class CloneablePtrControl : public SmartPtrControl {
public:
   virtual CloneablePtrControl *clone() const = 0;
   virtual void *get() = 0;

};


template<class T>
class CloneablePtrControlDerived : public CloneablePtrControl {
public:
   T d;

   CloneablePtrControlDerived(const T& x) : d(x) { }
   CloneablePtrControl *clone() const 
   {
      CloneablePtrControl *q = NTL_NEW_OP CloneablePtrControlDerived<T>(d);
      if (!q) MemoryError();
      return q;
   }
   void *get() { return &d; }
};



 
struct CloneablePtrLoopHole { };


template<class T>
class CloneablePtr {
private:
   T *dp;
   CloneablePtrControl *cp;

   void AddRef() const
   {
      if (cp) cp->cnt.inc();
   }

   void RemoveRef() const
   {
      if (cp && cp->cnt.dec()) { delete cp; }
   }

   class Dummy { };
   typedef void (CloneablePtr::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (CloneablePtr::*fake_null_type1)(Dummy1) const;

public:
   long get_count() const { return cp ? cp->cnt.get_count() : 0; }
   // mainly for debugging

   CloneablePtr() : dp(0), cp(0)  { }

   CloneablePtr(fake_null_type1) : dp(0), cp(0) { }

   CloneablePtr(CloneablePtrLoopHole, T* _dp, CloneablePtrControl *_cp) : dp(_dp), cp(_cp)
   { 
      AddRef();
   } 

   ~CloneablePtr() {
      RemoveRef();
   }

   CloneablePtr(const CloneablePtr& other) : dp(other.dp), cp(other.cp) 
   {
      AddRef();
   }


   CloneablePtr& operator=(const CloneablePtr& other)
   {
      CloneablePtr tmp(other);
      tmp.swap(*this);
      return *this;
   }

   template<class Y> friend class CloneablePtr;

   template<class Y>
   CloneablePtr(const CloneablePtr<Y>& other) : dp(other.dp), cp(other.cp) 
   {
      AddRef();
   }


   template<class Y>
   CloneablePtr& operator=(const CloneablePtr<Y>& other)
   {
      CloneablePtr tmp(other);
      tmp.swap(*this);
      return *this;
   }

#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   CloneablePtr(CloneablePtr&& other) noexcept : dp(other.dp), cp(other.cp) 
   {
      other.dp = 0;
      other.cp = 0;
   }

   CloneablePtr& operator=(CloneablePtr&& other) noexcept
   {
      CloneablePtr tmp(std::move(other));
      tmp.swap(*this);
      return *this;
   }

   template<class Y>
   CloneablePtr(CloneablePtr<Y>&& other) noexcept : dp(other.dp), cp(other.cp) 
   {
      other.dp = 0;
      other.cp = 0;
   }


   template<class Y>
   CloneablePtr& operator=(CloneablePtr<Y>&& other) noexcept
   {
      CloneablePtr tmp(std::move(other));
      tmp.swap(*this);
      return *this;
   }

#endif

   T& operator*()  const { return *dp; }
   T* operator->() const { return dp; }

   T* get() const { return dp; }

   void swap(CloneablePtr& other)
   {
      _ntl_swap(dp, other.dp);
      _ntl_swap(cp, other.cp);
   }

   operator fake_null_type() const 
   {
      return dp ?  &CloneablePtr::fake_null_function : 0;
   }

   template<class Y> 
   CloneablePtr<Y> DynamicCast() const 
   {
      if (!dp) 
         return CloneablePtr<Y>();
      else {
         Y* dp1 = dynamic_cast<Y *>(dp);
         if (!dp1) return CloneablePtr<Y>();
         return CloneablePtr<Y>(CloneablePtrLoopHole(), dp1, cp);
      }
   }

   CloneablePtr clone() const 
   {
      if (!dp) 
         return CloneablePtr();
      else {
         CloneablePtrControl *cp1 = cp->clone();
         char *complete = (char *) cp->get();
         char *complete1 = (char *) cp1->get();
         T *dp1 = (T *) (complete1 + (((char *)dp) - complete));
         return CloneablePtr(CloneablePtrLoopHole(), dp1, cp1);
      }
   }

   template<class Y>
   operator SmartPtr<Y>() { return SmartPtr<Y>(SmartPtrLoopHole(), dp, cp); }

};

template<class T> NTL_DECLARE_RELOCATABLE((CloneablePtr<T>*))


// free swap function
template<class T>
void swap(CloneablePtr<T>& p, CloneablePtr<T>& q) { p.swap(q); }

// free dynamic cast function
template<class X, class Y>
CloneablePtr<X> DynamicCast(const CloneablePtr<Y>& p)  { return p.template DynamicCast<X>(); }



// Equality testing

template<class X, class Y>
bool operator==(const CloneablePtr<X>& a, const CloneablePtr<Y>& b)
{
   return a.get() == b.get();
}


template<class X, class Y>
bool operator!=(const CloneablePtr<X>& a, const CloneablePtr<Y>& b)
{
   return a.get() != b.get();
}




// ******************************************************

// Implementation of MakeSmart and friends


#if (NTL_CXX_STANDARD >= 2011)

// Declared for backward compatibility with pre-C++11 NTL clients
template<class T> 
T& Fwd(T& x) { return x; }

template<class T> 
const T& Fwd(const T& x) { return x; }

template<class T>
class MakeSmartAux : public SmartPtrControl {
public: 
   T d;

   template<class... Args>
   MakeSmartAux(Args&&... args) : d(std::forward<Args>(args)...) { }
};

template<class T, class... Args>
SmartPtr<T> MakeSmart(Args&&... args)
{
   MakeSmartAux<T> *cp = 
      NTL_NEW_OP MakeSmartAux<T>( std::forward<Args>(args)...  ); 
   if (!cp) MemoryError();
   return SmartPtr<T>(SmartPtrLoopHole(), &cp->d, cp);
}

template<class T>
class MakeCloneableAux : public CloneablePtrControl {
public: 
   T d;

   template<class... Args>
   MakeCloneableAux(Args&&... args) : d(std::forward<Args>(args)...) { }
   CloneablePtrControl *clone() const \
   {
      CloneablePtrControl *q = NTL_NEW_OP CloneablePtrControlDerived<T>(d);
      if (!q) MemoryError();
      return q;
   }
   void *get() { return &d; }
};

#ifdef NTL_TEST_EXCEPTIONS

template<class T, class... Args>
T* MakeRaw(Args&&... args) { 
   T *p = 0;
   if (--exception_counter != 0) p = NTL_NEW_OP T(std::forward<Args>(args)...); 
   if (!p) MemoryError();
   return p;
};


#else

template<class T, class... Args>
T* MakeRaw(Args&&... args) { 
   T *p = NTL_NEW_OP T(std::forward<Args>(args)...); 
   if (!p) MemoryError();
   return p;
}

#endif


template<class T, class... Args>
CloneablePtr<T> MakeCloneable(Args&&... args)
{
   MakeCloneableAux<T> *cp = 
      NTL_NEW_OP MakeCloneableAux<T>( std::forward<Args>(args)...  ); 
   if (!cp) MemoryError();
   return CloneablePtr<T>(CloneablePtrLoopHole(), &cp->d, cp);
}

#else


// Reference forwarding

template<class T>
class ReferenceWrapper
{
private:
   T& x;
public:
   ReferenceWrapper(T& _x) : x(_x) { }
   operator T& () const { return x; }
};

template<class T> 
ReferenceWrapper<T> Fwd(T& x) { return ReferenceWrapper<T>(x); }

template<class T>
class ConstReferenceWrapper
{
private:
   T& x;
public:
   ConstReferenceWrapper(const T& _x) : x(_x) { }
   operator const T& () const { return x; }
};

template<class T> 
ConstReferenceWrapper<T> Fwd(const T& x) { return ConstReferenceWrapper<T>(x); }

template<class T>
T& UnwrapReference(const ReferenceWrapper<T>& x) { return x; } 

template<class T>
const T& UnwrapReference(const ConstReferenceWrapper<T>& x) { return x; } 

template<class T>
const T& UnwrapReference(const T& x) { return x; } 




// Some useful macros for simulating variadic templates

#define NTL_REPEATER_0(m) 
#define NTL_REPEATER_1(m)  m(1)
#define NTL_REPEATER_2(m)  m(1),m(2)
#define NTL_REPEATER_3(m)  m(1),m(2),m(3)
#define NTL_REPEATER_4(m)  m(1),m(2),m(3),m(4)
#define NTL_REPEATER_5(m)  m(1),m(2),m(3),m(4),m(5)
#define NTL_REPEATER_6(m)  m(1),m(2),m(3),m(4),m(5),m(6)
#define NTL_REPEATER_7(m)  m(1),m(2),m(3),m(4),m(5),m(6),m(7)
#define NTL_REPEATER_8(m)  m(1),m(2),m(3),m(4),m(5),m(6),m(7),m(8)
#define NTL_REPEATER_9(m)  m(1),m(2),m(3),m(4),m(5),m(6),m(7),m(8),m(9)

#define NTL_SEPARATOR_0 
#define NTL_SEPARATOR_1  ,
#define NTL_SEPARATOR_2  ,
#define NTL_SEPARATOR_3  ,
#define NTL_SEPARATOR_4  ,
#define NTL_SEPARATOR_5  ,
#define NTL_SEPARATOR_6  ,
#define NTL_SEPARATOR_7  ,
#define NTL_SEPARATOR_8  ,
#define NTL_SEPARATOR_9  ,

#define NTL_KEEP_NONZERO_0(x) 
#define NTL_KEEP_NONZERO_1(x)  x
#define NTL_KEEP_NONZERO_2(x)  x
#define NTL_KEEP_NONZERO_3(x)  x
#define NTL_KEEP_NONZERO_4(x)  x
#define NTL_KEEP_NONZERO_5(x)  x
#define NTL_KEEP_NONZERO_6(x)  x
#define NTL_KEEP_NONZERO_7(x)  x
#define NTL_KEEP_NONZERO_8(x)  x
#define NTL_KEEP_NONZERO_9(x)  x

#define NTL_FOREACH_ARG(m) \
   m(0) m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9)

#define NTL_FOREACH_ARG1(m) \
   m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9)

// ********************************

#define NTL_ARGTYPE(n) class X##n
#define NTL_ARGTYPES(n) NTL_REPEATER_##n(NTL_ARGTYPE)
#define NTL_MORE_ARGTYPES(n) NTL_SEPARATOR_##n NTL_REPEATER_##n(NTL_ARGTYPE)

#define NTL_VARARG(n) const X##n & x##n
#define NTL_VARARGS(n) NTL_REPEATER_##n(NTL_VARARG)

#define NTL_PASSTYPE(n) X ## n
#define NTL_PASSTYPES(n) NTL_REPEATER_##n(NTL_PASSTYPE)
#define NTL_MORE_PASSTYPES(n) NTL_SEPARATOR_##n NTL_REPEATER_##n(NTL_PASSTYPE)

#define NTL_PASSARG(n) x ## n
#define NTL_PASSARGS(n) NTL_REPEATER_##n(NTL_PASSARG)

#define NTL_UNWRAPARG(n) UnwrapReference(x ## n)
#define NTL_UNWRAPARGS(n) NTL_REPEATER_##n(NTL_UNWRAPARG)



// ********************************


#if 0

#define NTL_DEFINE_MAKESMART(n) \
template<class T  NTL_MORE_ARGTYPES(n)> \
class MakeSmartAux##n : public SmartPtrControl {\
public: T d; \
MakeSmartAux##n( NTL_VARARGS(n) ) : \
d( NTL_UNWRAPARGS(n) ) { }\
};\
\
template<class T NTL_MORE_ARGTYPES(n)>\
SmartPtr<T> MakeSmart( NTL_VARARGS(n) ) { \
   MakeSmartAux##n<T NTL_MORE_PASSTYPES(n) > *cp = \
   NTL_NEW_OP MakeSmartAux##n<T NTL_MORE_PASSTYPES(n)>( NTL_PASSARGS(n) ); \
   if (!cp) MemoryError();\
   return SmartPtr<T>(SmartPtrLoopHole(), &cp->d, cp);\
};\


NTL_FOREACH_ARG(NTL_DEFINE_MAKESMART)

#elif 1

// alternative implementation

#define NTL_DEFINE_SMART_CONSTRUCTOR(n) \
NTL_KEEP_NONZERO_##n(template< NTL_ARGTYPES(n) >) \
MakeSmartAux( NTL_VARARGS(n) ) : \
d( NTL_UNWRAPARGS(n) ) { }\


template<class T>
class MakeSmartAux : public SmartPtrControl {
public: T d; 
NTL_FOREACH_ARG(NTL_DEFINE_SMART_CONSTRUCTOR)
};

#define NTL_DEFINE_MAKESMART(n) \
template<class T NTL_MORE_ARGTYPES(n)>\
SmartPtr<T> MakeSmart( NTL_VARARGS(n) ) { \
   MakeSmartAux<T> *cp = \
   NTL_NEW_OP MakeSmartAux<T>( NTL_PASSARGS(n) ); \
   if (!cp) MemoryError();\
   return SmartPtr<T>(SmartPtrLoopHole(), &cp->d, cp);\
};\

NTL_FOREACH_ARG(NTL_DEFINE_MAKESMART)

#else

// alternative implementation


#define NTL_DEFINE_MAKESMART(n) \
template<class T> \
class MakeSmartAux##n : public SmartPtrControl {\
public: T d; \
NTL_KEEP_NONZERO_##n(template< NTL_ARGTYPES(n) >) \
MakeSmartAux##n( NTL_VARARGS(n) ) : \
d( NTL_UNWRAPARGS(n) ) { }\
};\
\
template<class T NTL_MORE_ARGTYPES(n)>\
SmartPtr<T> MakeSmart( NTL_VARARGS(n) ) { \
   MakeSmartAux##n<T> *cp = \
   NTL_NEW_OP MakeSmartAux##n<T>( NTL_PASSARGS(n) ); \
   if (!cp) MemoryError();\
   return SmartPtr<T>(SmartPtrLoopHole(), &cp->d, cp);\
};\

NTL_FOREACH_ARG(NTL_DEFINE_MAKESMART)

#endif





// ********************************


#define NTL_DEFINE_MAKECLONEABLE(n) \
template<class T  NTL_MORE_ARGTYPES(n)> \
class MakeCloneableAux##n : public CloneablePtrControl {\
public: T d; \
MakeCloneableAux##n( NTL_VARARGS(n) ) : \
d( NTL_UNWRAPARGS(n) ) { }\
CloneablePtrControl *clone() const \
{\
   CloneablePtrControl *q = NTL_NEW_OP CloneablePtrControlDerived<T>(d);\
   if (!q) MemoryError();\
   return q;\
}\
void *get() { return &d; }\
};\
\
template<class T NTL_MORE_ARGTYPES(n)>\
CloneablePtr<T> MakeCloneable( NTL_VARARGS(n) ) { \
   MakeCloneableAux##n<T NTL_MORE_PASSTYPES(n) > *cp = \
   NTL_NEW_OP MakeCloneableAux##n<T NTL_MORE_PASSTYPES(n)>( NTL_PASSARGS(n) ); \
   if (!cp) MemoryError();\
   return CloneablePtr<T>(CloneablePtrLoopHole(), &cp->d, cp);\
};\

NTL_FOREACH_ARG(NTL_DEFINE_MAKECLONEABLE)



// ********************************


#ifdef NTL_TEST_EXCEPTIONS

#define NTL_DEFINE_MAKERAW(n)\
template<class T  NTL_MORE_ARGTYPES(n)>\
T* MakeRaw(NTL_VARARGS(n)) { \
   T *p = 0; \
   if (--exception_counter != 0) p =  NTL_NEW_OP T(NTL_UNWRAPARGS(n)); \
   if (!p) MemoryError();\
   return p;\
};\


#else

#define NTL_DEFINE_MAKERAW(n)\
template<class T  NTL_MORE_ARGTYPES(n)>\
T* MakeRaw(NTL_VARARGS(n)) { \
   T *p = NTL_NEW_OP T(NTL_UNWRAPARGS(n)); \
   if (!p) MemoryError();\
   return p;\
};\

#endif


NTL_FOREACH_ARG(NTL_DEFINE_MAKERAW)

#endif

// ********************************


#ifdef NTL_TEST_EXCEPTIONS

template<class T>
T *MakeRawArray(long n)
{
   if (n < 0) LogicError("negative length in MakeRawArray");
   if (n == 0) return 0;
   T *p = 0; 
   if (--exception_counter != 0) p = new T[n];
   if (!p) MemoryError();
   return p;
}

#else

template<class T>
T *MakeRawArray(long n)
{
   if (n < 0) LogicError("negative length in MakeRawArray");
   if (n == 0) return 0;
   T *p = new T[n];
   if (!p) MemoryError();
   return p;
}

#endif



/**********************************************************************

UniquePtr<T> -- unique pointer to object with copying disabled.
Useful for pointers inside classes so that we can
automatically destruct them.  

Constructors:
   UniquePtr<T> p1;     // initialize with null
   UniquePtr<T> p1(0);

   T* rp;
   UniquePtr<T> p1(rp); // construct using raw pointer (explicit)

   p1 = 0;              // destroy's p1's referent and assigns null

   p1.make(...);        // destroy's p1's referent and assigns
                        // a fresh objected constructed via T(...),
                        // using psuedo variadic templates
                
   p1.reset(rp);        // destroy's p1's referent and assign rp

   if (!p1) ...         // test for null
   if (p1 == 0) ...

   if (p1) ...          // test for nonnull
   if (p1 != 0) ...

   if (p1 == p2) ...    // test for equality
   if (p1 != p2) ...   

   *p1                  // dereferencing
   p1->...


   rp = p1.get();       // fetch raw pointer
   rp = p1.release();   // fetch raw pointer, and set to NULL
   p1.move(p2);         // equivalent to p1.reset(p2.release()) --
                        // if p1 != p2 then:
                        //    makes p1 point to p2's referent,
                        //    setting p2 to NULL and destroying
                        //    p1's referent

   p1.swap(p2);         // fast swap
   swap(p1, p2);

   
**********************************************************************/



template<class T, class P=DefaultDeleterPolicy>
class UniquePtr {
private:
   T *dp;

   class Dummy { };
   typedef void (UniquePtr::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (UniquePtr::*fake_null_type1)(Dummy1) const;

   bool cannot_compare_these_types() const { return false; }

   UniquePtr(const UniquePtr&); // disabled
   void operator=(const UniquePtr&); // disabled

public:   
   explicit UniquePtr(T *p) : dp(p) { }

   UniquePtr() : dp(0) { }
   ~UniquePtr() { P::deleter(dp); }

#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   UniquePtr(UniquePtr&& other) noexcept : UniquePtr() 
   {
      this->move(other);
   }

   UniquePtr& operator=(UniquePtr&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif

   void reset(T* p = 0)
   {
      UniquePtr tmp(p);
      tmp.swap(*this);
   }

   UniquePtr& operator=(fake_null_type1) { reset(); return *this; }


#if (NTL_CXX_STANDARD >= 2011)

   template<class... Args>
   void make(Args&&... args) 
   {
      reset(MakeRaw<T>(std::forward<Args>(args)...));
   }

#else

   void make()
   {
      reset(MakeRaw<T>());
   }

#define NTL_DEFINE_UNIQUE_MAKE(n) \
   template< NTL_ARGTYPES(n) >\
   void make( NTL_VARARGS(n) )\
   {\
      reset(MakeRaw<T>( NTL_PASSARGS(n) ));\
   }\

   NTL_FOREACH_ARG1(NTL_DEFINE_UNIQUE_MAKE)

#endif

   T& operator*()  const { return *dp; }
   T* operator->() const { return dp; }

   T* get() const { return dp; }

   T* release() { T *p = dp; dp = 0; return p; }
   void move(UniquePtr& other) { reset(other.release()); }

   void swap(UniquePtr& other)
   {
      _ntl_swap(dp, other.dp);
   }


   operator fake_null_type() const 
   {
      return dp ?  &UniquePtr::fake_null_function : 0;
   }

};


template<class T, class P> NTL_DECLARE_RELOCATABLE((UniquePtr<T,P>*))


// free swap function
template<class T, class P>
void swap(UniquePtr<T,P>& p, UniquePtr<T,P>& q) { p.swap(q); }



// Equality testing

template<class T, class P>
bool operator==(const UniquePtr<T,P>& a, const UniquePtr<T,P>& b)
{
   return a.get() == b.get();
}

template<class T, class P>
bool operator!=(const UniquePtr<T,P>& a, const UniquePtr<T,P>& b)
{
   return a.get() != b.get();
}


// the following definitions of == and != prevent comparisons
// on UniquePtr's to different types...such comparisons
// don't make sense...defining these here ensures the compiler
// emits an error message...and a pretty readable one


template<class X, class Y, class U, class V>
bool operator==(const UniquePtr<X,U>& a, const UniquePtr<Y,V>& b)
{
   return a.cannot_compare_these_types();
}

template<class X, class Y, class U, class V>
bool operator!=(const UniquePtr<X,U>& a, const UniquePtr<Y,V>& b)
{
   return a.cannot_compare_these_types();
}



/**********************************************************************


     CopiedPtr: identical interface to UniquePtr, but copy constructor
     and assignment are defined, and both are implemented using the
     underlying type's copy constructor

     This provides very similar functionilty to OptionalVal, but I think
     it is simpler to provide the same interface as UniquePtr.

     It also allows some fine control of deleting and copying.
     This allows for "clone on copy" as well as other things,
     like a copying or cloning PIMPL pattern.


**********************************************************************/

struct DefaultCopierPolicy {

   template<class T>
   static T* copier(T *p) { return (p ?  MakeRaw<T>(*p) : 0); }

};

struct CloningCopier {

   template<class T>
   static T* copier(T *p) { return (p ?  p->clone() : 0); }

};

struct DefaultCopiedPtrPolicy : DefaultDeleterPolicy, DefaultCopierPolicy { };
struct CloningCopiedPtrPolicy : DefaultDeleterPolicy, CloningCopier { };

template<class T, class P = DefaultCopiedPtrPolicy>
class CopiedPtr {
private:
   T *dp;

   class Dummy { };
   typedef void (CopiedPtr::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (CopiedPtr::*fake_null_type1)(Dummy1) const;

   bool cannot_compare_these_types() const { return false; }

public:   
   explicit CopiedPtr(T *p) : dp(p) { }

   CopiedPtr() : dp(0) { }

   CopiedPtr(const CopiedPtr& other) : dp(0)
   {
      reset(P::copier(other.dp));
   }

   CopiedPtr& operator=(const CopiedPtr& other)
   {
      if (this == &other) return *this;
      CopiedPtr tmp(other);
      tmp.swap(*this);
      return *this;
   }


#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   CopiedPtr(CopiedPtr&& other) noexcept : CopiedPtr() 
   {
      this->move(other);
   }

   CopiedPtr& operator=(CopiedPtr&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif

   ~CopiedPtr() { P::deleter(dp); }

   void reset(T* p = 0)
   {
      CopiedPtr tmp(p);
      tmp.swap(*this);
   }

   CopiedPtr& operator=(fake_null_type1) { reset(); return *this; }


#if (NTL_CXX_STANDARD >= 2011)

   template<class... Args>
   void make(Args&&... args) 
   {
      reset(MakeRaw<T>(std::forward<Args>(args)...));
   }

#else

   void make()
   {
      reset(MakeRaw<T>());
   }

#define NTL_DEFINE_COPIED_MAKE(n) \
   template< NTL_ARGTYPES(n) >\
   void make( NTL_VARARGS(n) )\
   {\
      reset(MakeRaw<T>( NTL_PASSARGS(n) ));\
   }\

   NTL_FOREACH_ARG1(NTL_DEFINE_COPIED_MAKE)

#endif

   T& operator*()  const { return *dp; }
   T* operator->() const { return dp; }

   T* get() const { return dp; }

   T* release() { T *p = dp; dp = 0; return p; }
   void move(CopiedPtr& other) { reset(other.release()); }

   void swap(CopiedPtr& other)
   {
      _ntl_swap(dp, other.dp);
   }


   operator fake_null_type() const 
   {
      return dp ?  &CopiedPtr::fake_null_function : 0;
   }



};



template<class T, class P> NTL_DECLARE_RELOCATABLE((CopiedPtr<T,P>*))



// free swap function
template<class T, class P>
void swap(CopiedPtr<T,P>& p, CopiedPtr<T,P>& q) { p.swap(q); }



// Equality testing

template<class T, class P>
bool operator==(const CopiedPtr<T,P>& a, const CopiedPtr<T,P>& b)
{
   return a.get() == b.get();
}

template<class T, class P>
bool operator!=(const CopiedPtr<T,P>& a, const CopiedPtr<T,P>& b)
{
   return a.get() != b.get();
}


// the following definitions of == and != prevent comparisons
// on CopiedPtr's to different types...such comparisons
// don't make sense...defining these here ensures the compiler
// emits an error message...and a pretty readable one


template<class X, class Y, class U, class V>
bool operator==(const CopiedPtr<X,U>& a, const CopiedPtr<Y,V>& b)
{
   return a.cannot_compare_these_types();
}

template<class X, class Y, class U, class V>
bool operator!=(const CopiedPtr<X,U>& a, const CopiedPtr<Y,V>& b)
{
   return a.cannot_compare_these_types();
}





/**********************************************************************

OptionalVal<T> -- unique pointer to object with copying enabled.

Constructors:
   OptionalVal<T> p1;     // initialize with null

   T* rp;
   OptionalVal<T> p1(rp); // construct using raw pointer (explicit)

   OptionalVal<T> p2(p1); // construct a copy of p1's referrent

    

   p1.make(...);        // destroy's p1's referent and assigns
                        // a fresh objected constructed via T(...),
                        // using psuedo variadic templates
                
   p1.reset(rp);        // destroy's p1's referent and assign rp
   

   if (p1.exists()) ... // test for null

   p1.val()             // dereference

   rp = p1.get();       // fetch raw pointer
   rp = p1.release();   // fetch raw pointer, and set to NULL
   p1.move(p2);         // if p1 != p2 then:
                        //    makes p1 point to p2's referent,
                        //    setting p2 to NULL and destroying
                        //    p1's referent

   p1 = p2;             // if p1 != p2 then
                        //   if p2 == NULL then
                        //      reset p1
                        //   else 
                        //      p1.make(p2.val())

   p1.swap(p2);         // fast swap
   swap(p1, p2);

   
**********************************************************************/


template<class T>
class OptionalVal {
private:
   UniquePtr<T> dp;

public:   
   explicit OptionalVal(T *p) : dp(p) { }
   OptionalVal() { }

   OptionalVal(const OptionalVal& other) 
   {
      if (other.exists()) 
         make(other.val());
   }

   OptionalVal& operator=(const OptionalVal& other)
   {
      if (this == &other) return *this;
      OptionalVal tmp(other);
      tmp.swap(*this);
      return *this;
   }


#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   OptionalVal(OptionalVal&& other) noexcept : OptionalVal() 
   {
      this->move(other);
   }

   OptionalVal& operator=(OptionalVal&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif


   void reset(T* p = 0) { dp.reset(p); }

#if (NTL_CXX_STANDARD >= 2011)

   template<class... Args>
   void make(Args&&... args) 
   {
      dp.make(std::forward<Args>(args)...);
   }

#else

   void make() { dp.make(); }

#define NTL_DEFINE_OPTIONAL_VAL_MAKE(n) \
\
   template< NTL_ARGTYPES(n) >\
   void make( NTL_VARARGS(n) )\
   {\
      dp.make( NTL_PASSARGS(n) );\
   }\

   NTL_FOREACH_ARG1(NTL_DEFINE_OPTIONAL_VAL_MAKE)

#endif

   T& val() const { return *dp; }

   bool exists() const { return dp != 0; } 

   T* get() const { return dp.get(); }

   T* release() { return dp.release(); }

   void move(OptionalVal& other) { dp.move(other.dp); }

   void swap(OptionalVal& other) { dp.swap(other.dp); }

};


template<class T> NTL_DECLARE_RELOCATABLE((OptionalVal<T>*))


// free swap function
template<class T>
void swap(OptionalVal<T>& p, OptionalVal<T>& q) { p.swap(q); }






/**********************************************************************

UniqueArray<T> -- unique pointer to array of objects with copying disabled.
Useful for pointers inside classes so that we can
automatically destruct them.  

Constructors:
   UniqueArray<T> p1;     // initialize with null
   UniqueArray<T> p1(0); 

   T* rp;
   UniqueArray<T> p1(rp); // construct using raw pointer (explicit)

   p1 = 0;              // destroy's p1's referent and assigns null

   p1.SetLength(n);     // destroy's p1's referent and assigns
                        // a fresh objected constructed via new T[n]
                
   p1.reset(rp);        // destroy's p1's referent and assign rp

   if (!p1) ...         // test for null
   if (p1 == 0) ...

   if (p1) ...          // test for nonnull
   if (p1 != 0) ...

   if (p1 == p2) ...    // test for equality
   if (p1 != p2) ...   

   p1[i]                // array indexing

   rp = p1.get();       // fetch raw pointer
   rp = p1.release();   // fetch raw pointer, and set to NULL
   p1.move(p2);         // equivalent to p1.reset(p2.release()) --
                        // if p1 != p2 then:
                        //    makes p1 point to p2's referent,
                        //    setting p2 to NULL and destroying
                        //    p1's referent

   p1.swap(p2);         // fast swap
   swap(p1, p2);

   
**********************************************************************/


template<class T>
class UniqueArray {
private:
   T *dp;

   class Dummy { };
   typedef void (UniqueArray::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (UniqueArray::*fake_null_type1)(Dummy1) const;

   bool cannot_compare_these_types() const { return false; }

   UniqueArray(const UniqueArray&); // disabled
   void operator=(const UniqueArray&); // disabled

public:   
   explicit UniqueArray(T *p) : dp(p) { }

   UniqueArray() : dp(0) { }

   ~UniqueArray() { delete[] dp; }

#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   UniqueArray(UniqueArray&& other) noexcept : UniqueArray() 
   {
      this->move(other);
   }

   UniqueArray& operator=(UniqueArray&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif

   void reset(T* p = 0)
   {
      UniqueArray tmp(p);
      tmp.swap(*this);
   }

   UniqueArray& operator=(fake_null_type1) { reset(); return *this; }

   void SetLength(long n)
   {
      reset( MakeRawArray<T>(n) );
   }

   T& operator[](long i) const { return dp[i]; }

   T* get() const { return dp; }
   T *elts() const { return dp; }

   T* release() { T *p = dp; dp = 0; return p; }
   void move(UniqueArray& other) { reset(other.release()); }

   void swap(UniqueArray& other)
   {
      _ntl_swap(dp, other.dp);
   }

   operator fake_null_type() const 
   {
      return dp ?  &UniqueArray::fake_null_function : 0;
   }

};


template<class T> NTL_DECLARE_RELOCATABLE((UniqueArray<T>*))




// free swap function
template<class T>
void swap(UniqueArray<T>& p, UniqueArray<T>& q) { p.swap(q); }



// Equality testing

template<class X>
bool operator==(const UniqueArray<X>& a, const UniqueArray<X>& b)
{
   return a.get() == b.get();
}

template<class X>
bool operator!=(const UniqueArray<X>& a, const UniqueArray<X>& b)
{
   return a.get() != b.get();
}


// the following definitions of == and != prevent comparisons
// on UniqueArray's to different types...such comparisons
// don't make sense...defining these here ensures the compiler
// emits an error message...and a pretty readable one


template<class X, class Y>
bool operator==(const UniqueArray<X>& a, const UniqueArray<Y>& b)
{
   return a.cannot_compare_these_types();
}

template<class X, class Y>
bool operator!=(const UniqueArray<X>& a, const UniqueArray<Y>& b)
{
   return a.cannot_compare_these_types();
}





/**********************************************************************

Unique2DArray<T> -- unique pointer to array of arrays.

This is very similar to UniqueArray< UniqueArray<T> >, except that 
we can retrofit old code that excepts objects of type T**.

Constructors:
   Unique2DArray<T> p1;     // initialize with null
   Unique2DArray<T> p1(0);

   p1 = 0;              // destroy's p1's referent and assigns null
   p1.reset();

   p1.SetLength(n);     // destroy's p1's referent and assigns
                        // a fresh array of null pointers

   p1.SetDims(n, m)     // creates an n x m array
                
   if (!p1) ...         // test for null
   if (p1 == 0) ...

   if (p1) ...          // test for nonnull
   if (p1 != 0) ...

   if (p1 == p2) ...    // test for equality
   if (p1 != p2) ...   

   p1[i]                // array indexing

   T **rp;
   rp = p1.get();       // fetch raw pointer
   rp = p1.release();   // fetch raw pointer, and set to NULL
   p1.move(p2);         // if p1 != p2 then:
                        //    makes p1 point to p2's referent,
                        //    setting p2 to NULL and destroying
                        //    p1's referent

   p1.swap(p2);         // fast swap
   swap(p1, p2);

   
**********************************************************************/


template<class T>
class Unique2DArray {
public:
   typedef T *T_ptr;

private:
   UniqueArray<T_ptr> dp;
   long len;

   class Dummy { };
   typedef void (Unique2DArray::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (Unique2DArray::*fake_null_type1)(Dummy1) const;

   bool cannot_compare_these_types() const { return false; }

   Unique2DArray(const Unique2DArray&); // disabled
   void operator=(const Unique2DArray&); // disabled


public:   

   Unique2DArray() : len(0) { }

   ~Unique2DArray()
   {
      if (dp) {
         long i;
         for (i = 0; i < len; i++) delete [] dp[i];
      }
   }


#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   Unique2DArray(Unique2DArray&& other) noexcept : Unique2DArray() 
   {
      this->move(other);
   }

   Unique2DArray& operator=(Unique2DArray&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif

   void reset()
   {
      Unique2DArray tmp;
      tmp.swap(*this);
   }

   Unique2DArray& operator=(fake_null_type1) { reset(); return *this; }

   void SetLength(long n)
   {
      UniqueArray<T_ptr> tmp;
      tmp.SetLength(n);

      long i;
      for (i = 0; i < n; i++) tmp[i] = 0;

      reset();
      dp.move(tmp);
      len = n;
   }

   // EXCEPTIONS: strong ES
   void SetDims(long n, long m) 
   {
      Unique2DArray tmp;
      tmp.SetLength(n);
      
      long i;
      for (i = 0; i < n; i++)
         tmp[i] = MakeRawArray<T>(m);

      this->move(tmp); 
   }

   // EXCEPTIONS: strong ES
   // This is a special-purpose routine to help
   // with some legacy code...only rows 1..n-1 are allocated
   void SetDimsFrom1(long n, long m) 
   {
      Unique2DArray tmp;
      tmp.SetLength(n);
      
      long i;
      for (i = 1; i < n; i++)
         tmp[i] = MakeRawArray<T>(m);

      this->move(tmp); 
   }

   T_ptr& operator[](long i) const { return dp[i]; }

   T_ptr* get() const { return dp.get(); }

   T_ptr* release() { len = 0; return dp.release(); }


   void move(Unique2DArray& other) 
   { 
      Unique2DArray tmp;
      tmp.swap(other);
      tmp.swap(*this);
   }

   void swap(Unique2DArray& other)
   {
      dp.swap(other.dp);
      _ntl_swap(len, other.len);
   }

   operator fake_null_type() const 
   {
      return dp ?  &Unique2DArray::fake_null_function : 0;
   }

};


template<class T> NTL_DECLARE_RELOCATABLE((Unique2DArray<T>*))


// free swap function
template<class T>
void swap(Unique2DArray<T>& p, Unique2DArray<T>& q) { p.swap(q); }



// Equality testing

template<class X>
bool operator==(const Unique2DArray<X>& a, const Unique2DArray<X>& b)
{
   return a.get() == b.get();
}

template<class X>
bool operator!=(const Unique2DArray<X>& a, const Unique2DArray<X>& b)
{
   return a.get() != b.get();
}


// the following definitions of == and != prevent comparisons
// on Unique2DArray's to different types...such comparisons
// don't make sense...defining these here ensures the compiler
// emits an error message...and a pretty readable one


template<class X, class Y>
bool operator==(const Unique2DArray<X>& a, const Unique2DArray<Y>& b)
{
   return a.cannot_compare_these_types();
}

template<class X, class Y>
bool operator!=(const Unique2DArray<X>& a, const Unique2DArray<Y>& b)
{
   return a.cannot_compare_these_types();
}




// AlignedArray:
//
// specialized arrays that have similar interface to UniqueArray, but:
//  * they are allocated with a given alignment
//  * they (currently) only work on POD types
//
// DIRT:
// The current implementation just uses the _ntl_make_aligned function,
// which is not entirely portable.
// However, AlignedArray is currently only used if NTL_HAVE_AVX
// is defined, and under the assumptions imposed with that,
// it should definitely work.
//
// For now, this is not a part of the documented interface.

// This could all change in the future, if and when there is a more portable
// way of doing this.


template<class T, long align=NTL_DEFAULT_ALIGN>
class AlignedArray {
private:
   T *dp;
   char *sp;

   class Dummy { };
   typedef void (AlignedArray::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) const {}

   class Dummy1 { };
   typedef void (AlignedArray::*fake_null_type1)(Dummy1) const;

   bool cannot_compare_these_types() const { return false; }

   AlignedArray(const AlignedArray&); // disabled
   void operator=(const AlignedArray&); // disabled

   char* release() {  char *p = sp; dp = 0; sp = 0;  return p; }

   void reset(char* p)
   {
      AlignedArray tmp;
      if (p) {
         tmp.dp = (T*) _ntl_make_aligned(p, align);
         tmp.sp = p;
      }
      else {
         tmp.dp = 0;
         tmp.sp = 0;
      }

      tmp.swap(*this);
   }



public:   

   AlignedArray() : dp(0), sp(0) { }
   explicit AlignedArray(fake_null_type1) : dp(0), sp(0) { }

   ~AlignedArray() { NTL_SNS free(sp); }


#if (NTL_CXX_STANDARD >= 2011 && !defined(NTL_DISABLE_MOVE))

   AlignedArray(AlignedArray&& other) noexcept : AlignedArray() 
   {
      this->move(other);
   }

   AlignedArray& operator=(AlignedArray&& other) noexcept
   {
      this->move(other);
      return *this;
   }

#endif


   void reset() { reset(0); }

   AlignedArray& operator=(fake_null_type1) { reset(); return *this; }

   void SetLength(long n)
   {
      if (align <= 0 || n < 0) LogicError("AlignedArray::SetLength: bad args");
      if (NTL_OVERFLOW1(n, sizeof(T), align)) ResourceError("AlignedArray::SetLength: overflow");

      if (n == 0) {
         reset();
      }
      else {
	 char *p = (char *) NTL_SNS malloc(n*sizeof(T) + align);
         if (!p) MemoryError();
         reset(p);
      }
   }

   T& operator[](long i) const { return dp[i]; }

   T* get() const { return dp; }
   T* elts() const { return dp; }


   void move(AlignedArray& other) { reset(other.release()); }

   void swap(AlignedArray& other)
   {
      _ntl_swap(dp, other.dp);
      _ntl_swap(sp, other.sp);
   }

   operator fake_null_type() const 
   {
      return dp ?  &AlignedArray::fake_null_function : 0;
   }

};

template<class T, long align> 
NTL_DECLARE_RELOCATABLE((AlignedArray<T,align>*))


// free swap function
template<class T, long align>
void swap(AlignedArray<T,align>& p, AlignedArray<T,align>& q) { p.swap(q); }










NTL_CLOSE_NNS


#endif