This file is indexed.

/usr/include/NTL/SmartPtr.h is in libntl-dev 9.9.1-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
#ifndef NTL_SmartPtr__H
#define NTL_SmartPtr__H

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



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> p2 = 0;

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

  T *rp;
  SmartPtr<T> p4(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");

Also, there is an implicit conversion from the same, funny pointer type to
SmartPtr<T>, which is how one can use 0 to initialize and assign to a
SmartPtr<T>.

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 could be used to get the conversion from "0" to
work.

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

 


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


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


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



template<class T>
class SmartPtrControlDerived : public SmartPtrControl {
public:
   T* p;

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

   ~SmartPtrControlDerived() 
   { 
      delete 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 {}


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

   SmartPtr() : 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;
   }


   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);
   }

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

   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);
      }
   }


};


// 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 {}


public:
   CloneablePtr() : 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;
   }


   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);
   }

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

   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); }

};


// 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


// 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_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)



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



#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)




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


#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)


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


#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

   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 UniquePtr {
private:
   T *dp;

   class Dummy { };

   typedef void (UniquePtr::*fake_null_type)(Dummy) const;
   void fake_null_function(Dummy) 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() { delete dp; }

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

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

   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)

   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()); }

   template<class Y>
   void move(UniquePtr<Y>& other) { reset(other.release()); }

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

   UniquePtr(fake_null_type) : dp(0) { }

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

};


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



// Equality testing

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

template<class X>
bool operator!=(const UniquePtr<X>& a, const UniquePtr<X>& 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>
bool operator==(const UniquePtr<X>& a, const UniquePtr<Y>& b)
{
   return a.cannot_compare_these_types();
}

template<class X, class Y>
bool operator!=(const UniquePtr<X>& a, const UniquePtr<Y>& 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;
   }

   ~OptionalVal() {  }


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

   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)

   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); }

};


// 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

   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 {}

   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; }


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

   UniqueArray& operator=(fake_null_type) { 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);
   }

   UniqueArray(fake_null_type) : dp(0) { }

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

};



// 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

   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 {}

   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];
      }
   }

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

   Unique2DArray& operator=(fake_null_type) { 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);
   }

   Unique2DArray(fake_null_type) : dp(0), len(0) { }

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

};


// 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
// the current implementation uses posix_memalign, which seems
// to work on gcc and gcc clones (clang and icc).
// intended for use with Intel AVX intrinsics
//
// For now, this is not a part of the documented interface, and it is only
// works with __GNUC__.  If __GNUC__ is not defined, then it reverts to using
// malloc. Currently, it is only really needed if NTL_HAVE_AVX is defined,
// which anyway requires __GNUC__.
//
// This could all change in the future, if and when there is a more portable
// way of doing this.

// NOTE: the methods reset, free, and release are available, but should really
// only be used to move raw pointers around between compatible AlignedArray's.

// NOTE: posix_memalign has been in available since glibc 2.1.91, which is some
// time around the year 2000, so this should be portable.

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

   class Dummy { };

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

   bool cannot_compare_these_types() const { return false; }

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

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

   AlignedArray() : dp(0) { }

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


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

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

   void SetLength(long n)
   {
      using namespace std;
      // not clear if posix_memalign is in std:: or ::
      // this will make sure to find it in either case

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

      if (n == 0) {
         reset();
      }
      else
      {
	 void *p;

#ifdef __GNUC__
#define NTL_HAVE_ALIGNED_ARRAY
	 if (posix_memalign(&p, align, n*sizeof(T))) MemoryError();
#else
         p = malloc(n*sizeof(T));
         if (!p) MemoryError();
#endif

	 reset( (T*) p );
      }
   }

   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(AlignedArray& other) { reset(other.release()); }

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

   AlignedArray(fake_null_type) : dp(0) { }

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

};


// 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