Repository navigation
Expand file tree
/
Copy pathtests.cpp
More file actions
3942 lines (3272 loc) · 117 KB
/
Copy pathtests.cpp
File metadata and controls
3942 lines (3272 loc) · 117 KB
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
//Fully AI generated for the exercice
#include <gtest/gtest.h>
#include "vector.h"
// ---------------------------------------------------------------------------
// Instrumented element types
// ---------------------------------------------------------------------------
// Counts how many objects are alive, and how many times each special member
// ran. `live` going negative means a destructor ran on something that was
// never constructed. `live` staying positive after a scope means a leak.
struct Tracked {
static int live;
static int default_ctors;
static int copy_ctors;
static int assignments;
static int dtors;
int value;
Tracked() : value(0) { ++live; ++default_ctors; }
explicit Tracked(int v) : value(v) { ++live; ++default_ctors; }
Tracked(const Tracked& o) : value(o.value) { ++live; ++copy_ctors; }
Tracked& operator=(const Tracked& o) { value = o.value; ++assignments; return *this; }
~Tracked() { --live; ++dtors; }
static void reset() {
live = default_ctors = copy_ctors = assignments = dtors = 0;
}
};
int Tracked::live = 0;
int Tracked::default_ctors = 0;
int Tracked::copy_ctors = 0;
int Tracked::assignments = 0;
int Tracked::dtors = 0;
// Throws from its copy constructor once `budget` copies have been made.
struct ThrowOnCopy {
static int budget; // copies allowed before the next one throws
static int live;
int value;
explicit ThrowOnCopy(int v = 0) : value(v) { ++live; }
ThrowOnCopy(const ThrowOnCopy& o) : value(o.value) {
if (budget-- <= 0) throw std::runtime_error("copy ctor failed");
++live;
}
~ThrowOnCopy() { --live; }
static void reset(int b) { budget = b; live = 0; }
};
int ThrowOnCopy::budget = 0;
int ThrowOnCopy::live = 0;
// Throws from the DEFAULT constructor after `budget` successes. Needed to
// reach the count ctor, which ThrowOnCopy never exercises.
struct ThrowOnDefault {
static int budget;
static int live;
int value;
ThrowOnDefault() : value(0) {
if (budget-- <= 0) throw std::runtime_error("default ctor failed");
++live;
}
ThrowOnDefault(const ThrowOnDefault& o) : value(o.value) { ++live; }
~ThrowOnDefault() { --live; }
static void reset(int b) { budget = b; live = 0; }
};
int ThrowOnDefault::budget = 0;
int ThrowOnDefault::live = 0;
// No default constructor: only the fill and copy ctors may be instantiated
// for this type. Catches an accidental T() in the fill ctor at compile time.
struct NoDefault {
int value;
explicit NoDefault(int v) : value(v) {}
};
// Owns heap memory. A destructor call on raw bytes corrupts the heap; a
// missing destructor call leaks. Both show up under ASan.
struct Owning {
std::string* p;
explicit Owning(const char* s = "x") : p(new std::string(s)) {}
Owning(const Owning& o) : p(new std::string(*o.p)) {}
Owning& operator=(const Owning& o) {
*p = *o.p; // reuse the existing string, no realloc
return *this;
}
~Owning() { delete p; }
};
// Over-aligned: malloc only guarantees alignof(std::max_align_t).
struct alignas(64) OverAligned {
double payload[8];
OverAligned() : payload{} {}
};
// ---------------------------------------------------------------------------
// Default constructor
// ---------------------------------------------------------------------------
TEST(DefaultCtor, IsEmpty) {
vector<int> v;
EXPECT_EQ(v.size(), 0u);
EXPECT_EQ(v.capacity(), 0u);
}
TEST(DefaultCtor, DestructorOnEmptyIsSafe) {
// free(nullptr) is a no-op; the destroy loop runs zero times.
{ vector<int> v; }
SUCCEED();
}
// ---------------------------------------------------------------------------
// Count constructor
// ---------------------------------------------------------------------------
TEST(CountCtor, SetsSize) {
vector<int> v(5);
EXPECT_EQ(v.size(), 5u);
EXPECT_EQ(v.capacity(), 5u);
}
TEST(CountCtor, ZeroCountIsEmpty) {
vector<int> v(0);
EXPECT_EQ(v.size(), 0u);
EXPECT_EQ(v.capacity(), 0u) << "early return must leave capacity_ at 0";
}
TEST(CountCtor, SizeOneBoundary) {
vector<int> v(1);
ASSERT_EQ(v.size(), 1u);
EXPECT_EQ(v[0], 0);
}
TEST(CountCtor, ValueInitializesScalars) {
// The standard requires value-initialization: T() not T.
// If you ever switch the loop to `new (p) T;` this test starts failing
// (or reading garbage) for int.
vector<int> v(8);
for (vector<int>::size_type i = 0; i < v.size(); ++i) {
EXPECT_EQ(v[i], 0) << "element " << i << " was not value-initialized";
}
}
TEST(CountCtor, ValueInitializesTrivialAggregates) {
// Same distinction, for a struct with no user-provided constructor.
struct Point { int x; int y; };
vector<Point> v(3);
for (vector<Point>::size_type i = 0; i < v.size(); ++i) {
EXPECT_EQ(v[i].x, 0);
EXPECT_EQ(v[i].y, 0);
}
}
TEST(CountCtor, RunsOneDefaultCtorPerElement) {
Tracked::reset();
{
vector<Tracked> v(4);
EXPECT_EQ(Tracked::default_ctors, 4);
EXPECT_EQ(Tracked::live, 4);
EXPECT_EQ(Tracked::assignments, 0); // constructed, never assigned
}
EXPECT_EQ(Tracked::live, 0) << "destructor did not destroy every element";
}
// ---------------------------------------------------------------------------
// Fill constructor
// ---------------------------------------------------------------------------
TEST(FillCtor, SetsSizeAndValues) {
vector<int> v(3, 42);
ASSERT_EQ(v.size(), 3u);
EXPECT_EQ(v[0], 42);
EXPECT_EQ(v[1], 42);
EXPECT_EQ(v[2], 42);
}
TEST(FillCtor, ZeroCountIsEmpty) {
vector<int> v(0, 42);
EXPECT_EQ(v.size(), 0u);
EXPECT_EQ(v.capacity(), 0u);
}
TEST(FillCtor, ConstructsRatherThanAssigns) {
// This is the placement-new-vs-assignment distinction.
// `data_[i] = value` would show up here as assignments == 5.
Tracked::reset();
{
Tracked proto(7);
vector<Tracked> v(5, proto);
EXPECT_EQ(Tracked::copy_ctors, 5);
EXPECT_EQ(Tracked::assignments, 0);
EXPECT_EQ(Tracked::live, 6); // 5 elements + proto
EXPECT_EQ(v[0].value, 7);
EXPECT_EQ(v[4].value, 7);
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(FillCtor, EachElementIsIndependent) {
// Distinct objects, not one object referenced count times.
vector<Tracked> v(3, Tracked(1));
v[0].value = 99;
EXPECT_EQ(v[1].value, 1) << "elements share storage";
EXPECT_EQ(v[2].value, 1);
}
TEST(FillCtor, WorksForTypeWithNoDefaultCtor) {
// Only compiles if the fill ctor never needs T().
vector<NoDefault> v(3, NoDefault(5));
ASSERT_EQ(v.size(), 3u);
EXPECT_EQ(v[1].value, 5);
}
// ---------------------------------------------------------------------------
// Copy constructor
// ---------------------------------------------------------------------------
TEST(CopyCtor, PreservesSizeAndValues) {
vector<int> a(4, 9);
vector<int> b(a);
ASSERT_EQ(b.size(), a.size());
for (vector<int>::size_type i = 0; i < b.size(); ++i) {
EXPECT_EQ(b[i], 9);
}
}
TEST(CopyCtor, IsADeepCopy) {
// Requires operator[] to return a reference.
vector<int> a(3, 1);
vector<int> b(a);
b[0] = 99;
EXPECT_EQ(a[0], 1) << "writing to the copy modified the original";
EXPECT_EQ(b[0], 99);
}
TEST(CopyCtor, BuffersAreDistinct) {
vector<int> a(3, 1);
vector<int> b(a);
EXPECT_NE(&a[0], &b[0]) << "the copy points at the source's buffer";
}
TEST(CopyCtor, CopyConstructsEachElement) {
Tracked::reset();
{
vector<Tracked> a(3);
EXPECT_EQ(Tracked::live, 3);
vector<Tracked> b(a);
EXPECT_EQ(Tracked::copy_ctors, 3);
EXPECT_EQ(Tracked::live, 6) << "copy shares storage instead of owning its own";
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(CopyCtor, CopyingAnEmptyVectorIsSafe) {
vector<int> a;
vector<int> b(a);
EXPECT_EQ(b.size(), 0u);
EXPECT_EQ(b.capacity(), 0u);
}
TEST(CopyCtor, AcceptsAConstSource) {
// Fails to compile if size() or operator[] is missing its const overload.
const vector<int> a(2, 5);
vector<int> b(a);
EXPECT_EQ(b.size(), 2u);
EXPECT_EQ(b[1], 5);
}
TEST(CopyCtor, CapacityMatchesWhatWasAllocated) {
// The ctor allocates other.size() elements, so capacity_ must be
// other.size() too. Copying other.capacity_ instead would claim room the
// buffer doesn't have, and the first push_back would run off the end.
vector<int> a(4, 1);
vector<int> b(a);
EXPECT_EQ(b.capacity(), b.size());
}
TEST(CopyCtor, SurvivesTheSourceGoingAway) {
vector<int>* a = new vector<int>(3, 8);
vector<int> b(*a);
delete a;
EXPECT_EQ(b[0], 8) << "the copy was pointing into the source's buffer";
EXPECT_EQ(b[2], 8);
}
TEST(CopyCtor, NestedVectors) {
// Exercises the copy ctor recursively: T is itself a vector.
vector<vector<int>> a(2, vector<int>(3, 7));
vector<vector<int>> b(a);
ASSERT_EQ(b.size(), 2u);
ASSERT_EQ(b[0].size(), 3u);
EXPECT_EQ(b[1][2], 7);
b[0][0] = 100;
EXPECT_EQ(a[0][0], 7) << "inner buffers are shared between the copies";
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
TEST(Dtor, DestroysExactlyOncePerElement) {
Tracked::reset();
{
vector<Tracked> v(10);
}
EXPECT_EQ(Tracked::dtors, 10);
EXPECT_EQ(Tracked::live, 0);
}
TEST(Dtor, ReleasesElementResources) {
// Run under ASan: a missing ~T() leaks 16 std::strings.
{ vector<Owning> v(16, Owning("hello")); }
SUCCEED();
}
// ---------------------------------------------------------------------------
// Exception safety
// ---------------------------------------------------------------------------
// A constructor that throws never completes, so ~vector() is NOT called for it.
// Whatever the constructor already built is therefore its own responsibility:
// destroy the elements placement new actually reached, free the buffer, rethrow.
//
// Destroying too many is undefined behaviour (~T() on raw bytes); destroying too
// few leaks. `live` catches both -- below the expected value means
// over-destruction, above means a leak.
TEST(ExceptionSafety, FillCtorDestroysOnlyConstructedElements) {
ThrowOnCopy::reset(/*budget=*/3);
ThrowOnCopy proto(1);
ASSERT_EQ(ThrowOnCopy::live, 1);
EXPECT_THROW({ vector<ThrowOnCopy> v(10, proto); }, std::runtime_error);
// The 3 successful copies are destroyed, the 7 slots placement new never
// reached are left alone, the buffer is freed. Only proto survives.
EXPECT_EQ(ThrowOnCopy::live, 1);
}
TEST(ExceptionSafety, FillCtorThrowOnTheVeryFirstElement) {
ThrowOnCopy::reset(/*budget=*/0);
ThrowOnCopy proto(1);
EXPECT_THROW({ vector<ThrowOnCopy> v(4, proto); }, std::runtime_error);
// size_ is still 0, so the cleanup loop must not run at all.
EXPECT_EQ(ThrowOnCopy::live, 1);
}
TEST(ExceptionSafety, FillCtorThrowOnTheLastElement) {
ThrowOnCopy::reset(/*budget=*/3);
ThrowOnCopy proto(1);
EXPECT_THROW({ vector<ThrowOnCopy> v(4, proto); }, std::runtime_error);
EXPECT_EQ(ThrowOnCopy::live, 1);
}
TEST(ExceptionSafety, FillCtorPropagatesTheOriginalException) {
// partial_destruction() ends in a bare `throw;`. That is a rethrow of the
// exception currently being handled -- legal only because the function is
// called from inside a catch block. Outside one it would call terminate.
ThrowOnCopy::reset(/*budget=*/1);
ThrowOnCopy proto(1);
try {
vector<ThrowOnCopy> v(5, proto);
FAIL() << "expected the copy ctor to throw";
} catch (const std::runtime_error& e) {
EXPECT_STREQ(e.what(), "copy ctor failed");
} catch (...) {
FAIL() << "the wrong exception type escaped";
}
}
TEST(ExceptionSafety, CountCtorDestroysOnlyConstructedElements) {
// T() can throw just as easily as T(value); the count ctor needs the same
// cleanup as the fill ctor. A missing (or dead) try block shows up here as
// `live` stuck at 3 -- the already-built elements were never destroyed.
ThrowOnDefault::reset(/*budget=*/3);
EXPECT_THROW({ vector<ThrowOnDefault> v(10); }, std::runtime_error);
EXPECT_EQ(ThrowOnDefault::live, 0)
<< "count ctor leaked the elements it had already constructed";
}
TEST(ExceptionSafety, CountCtorThrowOnTheVeryFirstElement) {
ThrowOnDefault::reset(/*budget=*/0);
EXPECT_THROW({ vector<ThrowOnDefault> v(4); }, std::runtime_error);
EXPECT_EQ(ThrowOnDefault::live, 0);
}
TEST(ExceptionSafety, CopyCtorCleansUpPartialWork) {
ThrowOnCopy::reset(/*budget=*/100);
{
vector<ThrowOnCopy> source(6, ThrowOnCopy(2));
ASSERT_EQ(ThrowOnCopy::live, 6); // the temporary proto is already gone
ThrowOnCopy::budget = 2; // allow only 2 of the 6 copies
EXPECT_THROW({ vector<ThrowOnCopy> copy(source); },
std::runtime_error);
EXPECT_EQ(ThrowOnCopy::live, 6) << "the failed copy damaged the source";
}
EXPECT_EQ(ThrowOnCopy::live, 0);
}
TEST(ExceptionSafety, FailedConstructionLeaksNoBuffer) {
// Purely an ASan/valgrind check: the malloc'd block must be freed on the
// throwing path. Looping makes any leak big enough to be obvious.
for (int i = 0; i < 100; ++i) {
ThrowOnCopy::reset(/*budget=*/5);
ThrowOnCopy proto(1);
EXPECT_THROW({ vector<ThrowOnCopy> v(1000, proto); }, std::runtime_error);
}
SUCCEED();
}
// ---------------------------------------------------------------------------
// Allocation edge cases
// ---------------------------------------------------------------------------
TEST(Alloc, HugeRequestThrowsBadAlloc) {
// malloc returns nullptr rather than throwing, so allocate_raw has to check
// and `throw std::bad_alloc();` itself. A bare `throw;` here would call
// terminate: there is no exception in flight to rethrow.
const auto huge = std::numeric_limits<vector<int>::size_type>::max() / 2;
EXPECT_THROW({ vector<int> v(huge); }, std::length_error);
}
TEST(Alloc, DISABLED_SizeOverflowIsDetected) {
// count * sizeof(T) wraps around, so a small block gets allocated and the
// constructor then writes far past it. Needs an explicit check before the
// multiplication:
// if (count > std::numeric_limits<size_type>::max() / sizeof(T))
// throw std::length_error("vector too long");
using ST = vector<std::int64_t>::size_type;
const ST count = std::numeric_limits<ST>::max() / 4 + 1; // *8 overflows
EXPECT_THROW({ vector<std::int64_t> v(count); }, std::length_error);
}
TEST(Alloc, DISABLED_RespectsOverAlignedTypes) {
// malloc only guarantees alignof(std::max_align_t), typically 16. A
// 64-byte-aligned element needs aligned_alloc, or the aligned overload of
// ::operator new.
vector<OverAligned> v(4);
for (vector<OverAligned>::size_type i = 0; i < v.size(); ++i) {
auto addr = reinterpret_cast<std::uintptr_t>(&v[i]);
EXPECT_EQ(addr % alignof(OverAligned), 0u) << "element " << i << " misaligned";
}
}
// ---------------------------------------------------------------------------
// Accessors
// ---------------------------------------------------------------------------
TEST(Accessors, SubscriptReturnsAReference) {
vector<int> v(3, 1);
v[1] = 77;
EXPECT_EQ(v[1], 77) << "operator[] returns by value, so the write was discarded";
}
TEST(Accessors, ElementsAreContiguous) {
vector<int> v(4, 0);
EXPECT_EQ(&v[0] + 1, &v[1]);
EXPECT_EQ(&v[0] + 3, &v[3]);
}
TEST(Accessors, ConstSubscriptReturnsAConstReference) {
const vector<int> v(3, 5);
const int& r = v[0];
EXPECT_EQ(r, 5);
EXPECT_EQ(&r, &v[0]) << "const operator[] handed back a temporary copy";
}
TEST(Accessors, SizeAndCapacityAreCallableOnConst) {
const vector<int> v(2, 1);
EXPECT_EQ(v.size(), 2u);
EXPECT_EQ(v.capacity(), 2u);
}
// ---------------------------------------------------------------------------
// Move constructor
// ---------------------------------------------------------------------------
TEST(MoveCtor, IsMarkedNoexcept) {
// Without this, vector's own reallocation logic falls back to copying
// (std::move_if_noexcept), and every growth silently loses the speedup.
static_assert(std::is_nothrow_move_constructible<vector<int>>::value,
"the move constructor must be noexcept");
SUCCEED();
}
TEST(MoveCtor, TransfersSizeAndValues) {
vector<int> a(4, 9);
vector<int> b(std::move(a));
ASSERT_EQ(b.size(), 4u);
EXPECT_EQ(b.capacity(), 4u);
EXPECT_EQ(b[0], 9);
EXPECT_EQ(b[3], 9);
}
TEST(MoveCtor, StealsTheBufferRatherThanCopyingIt) {
// The defining property: the new vector points at the SAME memory.
vector<int> a(3, 1);
const int* old_buffer = &a[0];
vector<int> b(std::move(a));
EXPECT_EQ(&b[0], old_buffer) << "the buffer was reallocated, not transferred";
}
TEST(MoveCtor, LeavesTheSourceEmpty) {
// "Valid but unspecified" -- empty is the conventional choice, and it is
// what stops the source's destructor from freeing the stolen buffer.
vector<int> a(5, 1);
vector<int> b(std::move(a));
EXPECT_EQ(a.size(), 0u);
EXPECT_EQ(a.capacity(), 0u);
}
TEST(MoveCtor, ConstructsNoElements) {
// No allocation and no element construction: only three scalars are read
// and three are written.
Tracked::reset();
{
vector<Tracked> a(6);
ASSERT_EQ(Tracked::default_ctors, 6);
vector<Tracked> b(std::move(a));
EXPECT_EQ(Tracked::copy_ctors, 0) << "the move ctor copied the elements";
EXPECT_EQ(Tracked::default_ctors, 6) << "extra elements were constructed";
EXPECT_EQ(Tracked::dtors, 0) << "the move ctor destroyed something";
EXPECT_EQ(Tracked::live, 6);
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(MoveCtor, ElementsAreDestroyedExactlyOnce) {
// The moved-from vector must NOT destroy the elements it gave away.
// A double destruction shows up as live == -6.
Tracked::reset();
{
vector<Tracked> a(6);
vector<Tracked> b(std::move(a));
}
EXPECT_EQ(Tracked::dtors, 6) << "elements were destroyed twice, or not at all";
EXPECT_EQ(Tracked::live, 0);
}
TEST(MoveCtor, MovedFromSourceIsSafeToDestroy) {
// Run under ASan: if data_ was not nulled, both destructors free the same
// block and this is a double free.
{
vector<Owning> a(8, Owning("payload"));
vector<Owning> b(std::move(a));
}
SUCCEED();
}
TEST(MoveCtor, SourceOutlivingTheDestinationIsSafe) {
// Reverse lifetime order: the destination dies first and frees the buffer.
// The source must not touch it afterwards.
vector<Owning> a(4, Owning("payload"));
{
vector<Owning> b(std::move(a));
}
EXPECT_EQ(a.size(), 0u);
}
TEST(MoveCtor, MovingAnEmptyVectorIsSafe) {
vector<int> a;
vector<int> b(std::move(a));
EXPECT_EQ(b.size(), 0u);
EXPECT_EQ(b.capacity(), 0u);
EXPECT_EQ(a.size(), 0u);
}
TEST(MoveCtor, MovedFromVectorCanBeCopiedFrom) {
// The source must be a usable object, not merely destructible.
vector<int> a(3, 1);
vector<int> b(std::move(a));
vector<int> c(a); // copy of the empty moved-from vector
EXPECT_EQ(c.size(), 0u);
}
TEST(MoveCtor, ChainedMovesKeepOneOwner) {
vector<int> a(3, 4);
const int* buffer = &a[0];
vector<int> b(std::move(a));
vector<int> c(std::move(b));
EXPECT_EQ(&c[0], buffer) << "the buffer was copied somewhere along the chain";
EXPECT_EQ(a.size(), 0u);
EXPECT_EQ(b.size(), 0u);
EXPECT_EQ(c.size(), 3u);
}
TEST(MoveCtor, PreferredOverCopyForRvalues) {
// Overload resolution check: an rvalue must select vector(vector&&).
// If the move ctor is missing, this silently binds to the copy ctor and
// copy_ctors becomes 4.
Tracked::reset();
{
vector<Tracked> a(4);
vector<Tracked> b(static_cast<vector<Tracked>&&>(a));
EXPECT_EQ(Tracked::copy_ctors, 0) << "an rvalue selected the copy ctor";
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(MoveCtor, LvaluesStillSelectTheCopyCtor) {
// The mirror image: adding a move ctor must not divert plain copies.
Tracked::reset();
{
vector<Tracked> a(4);
vector<Tracked> b(a);
EXPECT_EQ(Tracked::copy_ctors, 4) << "an lvalue was moved from";
EXPECT_EQ(a.size(), 4u) << "the source was gutted by a copy";
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(MoveCtor, WorksForElementsThatCannotBeCopied) {
// ThrowOnCopy throws once its budget runs out. With budget 0 any element
// copy fails, so this only passes if the move genuinely copies nothing.
ThrowOnCopy::reset(/*budget=*/6);
{
ThrowOnCopy proto(1);
vector<ThrowOnCopy> a(6, proto);
ASSERT_EQ(ThrowOnCopy::budget, 0);
EXPECT_NO_THROW({ vector<ThrowOnCopy> b(std::move(a)); });
}
EXPECT_EQ(ThrowOnCopy::live, 0);
}
TEST(MoveCtor, NestedVectors) {
vector<vector<int>> a(2, vector<int>(3, 7));
const int* inner = &a[0][0];
vector<vector<int>> b(std::move(a));
ASSERT_EQ(b.size(), 2u);
EXPECT_EQ(b[1][2], 7);
EXPECT_EQ(&b[0][0], inner) << "the inner buffers were reallocated";
EXPECT_EQ(a.size(), 0u);
}
TEST(MoveCtor, LargeVectorCostsNothing) {
// Not a timing test -- just proof that no per-element work happens for a
// vector far too large to copy cheaply.
Tracked::reset();
{
vector<Tracked> a(10000);
Tracked::copy_ctors = 0;
vector<Tracked> b(std::move(a));
EXPECT_EQ(Tracked::copy_ctors, 0);
}
EXPECT_EQ(Tracked::live, 0);
}
// Copy assignment tests -- paste into vector_test.cpp after the move ctor
// section. Reuses Tracked, ThrowOnCopy, NoDefault and Owning.
//
// The three branches under test:
// A. capacity_ < other.size_ -> reallocate (strong guarantee)
// B. size_ < other.size_ -> assign prefix, construct the rest (basic)
// C. size_ >= other.size_ -> assign prefix, destroy the tail (basic)
// Throws from operator= after `budget` successful assignments. The copy ctor
// never throws, so only the reuse branches are affected.
struct ThrowOnAssign {
static int budget;
static int live;
int value;
explicit ThrowOnAssign(int v = 0) : value(v) { ++live; }
ThrowOnAssign(const ThrowOnAssign& o) : value(o.value) { ++live; }
ThrowOnAssign& operator=(const ThrowOnAssign& o) {
if (budget-- <= 0) throw std::runtime_error("assignment failed");
value = o.value;
return *this;
}
~ThrowOnAssign() { --live; }
static void reset(int b) { budget = b; live = 0; }
};
int ThrowOnAssign::budget = 0;
int ThrowOnAssign::live = 0;
// ---------------------------------------------------------------------------
// Return value and chaining
// ---------------------------------------------------------------------------
TEST(CopyAssign, ReturnsReferenceToThis) {
vector<int> a(2, 1);
vector<int> b(3, 7);
vector<int>& r = (a = b);
EXPECT_EQ(&r, &a) << "operator= returned a copy instead of *this";
}
TEST(CopyAssign, SupportsChaining) {
vector<int> a(1, 0), b(1, 0), c(3, 5);
a = b = c;
ASSERT_EQ(a.size(), 3u);
ASSERT_EQ(b.size(), 3u);
EXPECT_EQ(a[2], 5);
EXPECT_EQ(b[2], 5);
}
// ---------------------------------------------------------------------------
// Self-assignment
// ---------------------------------------------------------------------------
TEST(CopyAssign, SelfAssignmentPreservesContents) {
// Without the this == &other guard, the reuse branches read and write the
// same buffer and the tail gets destroyed after being "copied".
vector<int> a(4, 3);
a = a;
ASSERT_EQ(a.size(), 4u);
for (vector<int>::size_type i = 0; i < a.size(); ++i) EXPECT_EQ(a[i], 3);
}
TEST(CopyAssign, SelfAssignmentDoesNoWork) {
Tracked::reset();
{
vector<Tracked> a(4);
Tracked::assignments = 0;
Tracked::dtors = 0;
a = a;
EXPECT_EQ(Tracked::assignments, 0) << "self-assignment did element work";
EXPECT_EQ(Tracked::dtors, 0) << "self-assignment destroyed elements";
EXPECT_EQ(Tracked::live, 4);
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(CopyAssign, SelfAssignmentThroughAReferenceIsSafe) {
// The realistic way self-assignment happens.
vector<Owning> a(3, Owning("payload"));
const vector<Owning>& alias = a;
a = alias;
EXPECT_EQ(a.size(), 3u);
}
// ---------------------------------------------------------------------------
// Branch A: reallocation (capacity_ < other.size_)
// ---------------------------------------------------------------------------
TEST(CopyAssign, GrowingBeyondCapacityReallocates) {
vector<int> a(2, 1);
vector<int> b(10, 4);
a = b;
ASSERT_EQ(a.size(), 10u);
EXPECT_GE(a.capacity(), 10u);
EXPECT_EQ(a[0], 4);
EXPECT_EQ(a[9], 4);
}
TEST(CopyAssign, GrowingFromEmpty) {
vector<int> a;
vector<int> b(3, 6);
a = b;
ASSERT_EQ(a.size(), 3u);
EXPECT_EQ(a[1], 6);
}
TEST(CopyAssign, ReallocationDestroysTheOldElements) {
Tracked::reset();
{
vector<Tracked> a(2);
vector<Tracked> b(10);
ASSERT_EQ(Tracked::live, 12);
a = b;
// a's 2 old elements destroyed, 10 new copies built: 10 + 10 = 20 live.
EXPECT_EQ(Tracked::live, 20) << "old elements leaked or were double-destroyed";
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(CopyAssign, ReallocationUsesCopyConstructionNotAssignment) {
// Nothing exists in the fresh buffer, so every element must be constructed.
Tracked::reset();
{
vector<Tracked> a(2);
vector<Tracked> b(10);
Tracked::copy_ctors = 0;
Tracked::assignments = 0;
a = b;
EXPECT_EQ(Tracked::copy_ctors, 10);
EXPECT_EQ(Tracked::assignments, 0) << "assigned into raw memory";
}
EXPECT_EQ(Tracked::live, 0);
}
// ---------------------------------------------------------------------------
// Branch B: growing within existing capacity
// ---------------------------------------------------------------------------
TEST(CopyAssign, GrowingWithinCapacityReusesTheBuffer) {
// Build spare capacity by assigning a large vector then a smaller one.
vector<int> a(10, 1);
vector<int> small(2, 2);
a = small;
ASSERT_EQ(a.size(), 2u);
const int* buffer = &a[0];
vector<int> mid(7, 3);
a = mid; // 7 <= capacity, no reallocation expected
ASSERT_EQ(a.size(), 7u);
EXPECT_EQ(&a[0], buffer) << "reallocated despite sufficient capacity";
EXPECT_EQ(a[0], 3);
EXPECT_EQ(a[6], 3);
}
TEST(CopyAssign, GrowingWithinCapacityMixesAssignmentAndConstruction) {
Tracked::reset();
{
vector<Tracked> a(10);
vector<Tracked> two(2);
a = two; // a now size 2, capacity 10
ASSERT_EQ(a.size(), 2u);
vector<Tracked> seven(7);
Tracked::assignments = 0;
Tracked::copy_ctors = 0;
a = seven;
EXPECT_EQ(Tracked::assignments, 2) << "the existing 2 elements should be assigned";
EXPECT_EQ(Tracked::copy_ctors, 5) << "the 5 new slots should be constructed";
}
EXPECT_EQ(Tracked::live, 0);
}
// ---------------------------------------------------------------------------
// Branch C: shrinking
// ---------------------------------------------------------------------------
TEST(CopyAssign, ShrinkingKeepsTheBufferAndCapacity) {
vector<int> a(10, 1);
const int* buffer = &a[0];
const auto cap = a.capacity();
vector<int> b(3, 8);
a = b;
ASSERT_EQ(a.size(), 3u);
EXPECT_EQ(&a[0], buffer) << "shrinking should not reallocate";
EXPECT_EQ(a.capacity(), cap) << "shrinking should not reduce capacity";
EXPECT_EQ(a[2], 8);
}
TEST(CopyAssign, ShrinkingDestroysTheTail) {
Tracked::reset();
{
vector<Tracked> a(10);
vector<Tracked> b(3);
ASSERT_EQ(Tracked::live, 13);
a = b;
// a: 3 assigned-over survivors + 7 destroyed. b: 3. Total 6.
EXPECT_EQ(Tracked::live, 6) << "tail elements were leaked or double-destroyed";
EXPECT_EQ(a.size(), 3u);
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(CopyAssign, ShrinkingReleasesTailResources) {
// ASan: the 7 discarded strings must be freed, exactly once.
vector<Owning> a(10, Owning("payload"));
vector<Owning> b(3, Owning("payload"));
a = b;
EXPECT_EQ(a.size(), 3u);
}
TEST(CopyAssign, AssigningEmptyEmptiesTheTarget) {
Tracked::reset();
{
vector<Tracked> a(5);
vector<Tracked> empty;
a = empty;
EXPECT_EQ(a.size(), 0u);
EXPECT_EQ(Tracked::live, 0) << "elements were not destroyed";
}
EXPECT_EQ(Tracked::live, 0);
}
TEST(CopyAssign, SameSizeAssignsEveryElement) {
Tracked::reset();
{
vector<Tracked> a(4);
vector<Tracked> b(4);
Tracked::assignments = 0;
Tracked::copy_ctors = 0;
Tracked::dtors = 0;
a = b;
EXPECT_EQ(Tracked::assignments, 4);
EXPECT_EQ(Tracked::copy_ctors, 0) << "constructed instead of assigned";
EXPECT_EQ(Tracked::dtors, 0) << "destroyed instead of assigned";
}
EXPECT_EQ(Tracked::live, 0);
}
// ---------------------------------------------------------------------------
// Independence and source integrity
// ---------------------------------------------------------------------------
TEST(CopyAssign, ResultIsIndependentOfTheSource) {
vector<int> a(2, 1);
vector<int> b(5, 9);
a = b;
a[0] = 100;
EXPECT_EQ(b[0], 9) << "assignment produced a shallow copy";
EXPECT_NE(&a[0], &b[0]);
}
TEST(CopyAssign, SourceIsUnchanged) {
vector<int> a(2, 1);
vector<int> b(5, 9);
a = b;
ASSERT_EQ(b.size(), 5u);
EXPECT_EQ(b[4], 9);
}
TEST(CopyAssign, TargetSurvivesTheSourceGoingAway) {
vector<int> a(1, 0);
{
vector<int> b(4, 2);
a = b;
}
ASSERT_EQ(a.size(), 4u);
EXPECT_EQ(a[3], 2);
}
TEST(CopyAssign, RepeatedAssignmentDoesNotLeak) {
// ASan: a missing free on the reallocating path shows up here.
vector<Owning> a;
for (int i = 0; i < 200; ++i) {
vector<Owning> b(static_cast<vector<Owning>::size_type>(i % 20 + 1),
Owning("payload"));
a = b;
}
SUCCEED();
}
TEST(CopyAssign, WorksForTypeWithNoDefaultCtor) {
// Assignment must never need T(). Fails to compile if the reallocating
// branch default-constructs before assigning.
vector<NoDefault> a(2, NoDefault(1));
vector<NoDefault> b(5, NoDefault(9));
a = b;
ASSERT_EQ(a.size(), 5u);
EXPECT_EQ(a[4].value, 9);
}
TEST(CopyAssign, ElementsRemainContiguous) {
vector<int> a(2, 1);
vector<int> b(6, 3);
a = b;
EXPECT_EQ(&a[0] + 5, &a[5]);
}
// ---------------------------------------------------------------------------
// Exception safety
// ---------------------------------------------------------------------------
TEST(CopyAssign, ReallocatingBranchGivesTheStrongGuarantee) {
// The new buffer is built before the old one is touched, so a throw must
// leave the target exactly as it was.
ThrowOnCopy::reset(/*budget=*/1000);
{
ThrowOnCopy proto(1);
vector<ThrowOnCopy> a(3, proto);
vector<ThrowOnCopy> b(20, proto);
const ThrowOnCopy* buffer = &a[0];