Repository navigation
Expand file tree
/
Copy pathtest_cpp_move_semantics.py
More file actions
1478 lines (1222 loc) · 45.3 KB
/
Copy pathtest_cpp_move_semantics.py
File metadata and controls
1478 lines (1222 loc) · 45.3 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
"""
Comprehensive C++ move semantics testing.
Tests rvalue references, move constructors, move assignments, perfect forwarding,
std::move, std::forward, and various move optimization patterns.
"""
from pathlib import Path
from typing import cast
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def cpp_move_semantics_project(temp_repo: Path) -> Path:
"""Create a comprehensive C++ project with move semantics patterns."""
project_path = temp_repo / "cpp_move_semantics_test"
project_path.mkdir()
# Create basic structure
(project_path / "src").mkdir()
(project_path / "include").mkdir()
return project_path
def test_basic_move_semantics(
cpp_move_semantics_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test basic move constructors and move assignment operators."""
test_file = cpp_move_semantics_project / "basic_move_semantics.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <utility>
// Class demonstrating move semantics
class MoveableResource {
private:
std::string* data_;
size_t size_;
public:
// Constructor
MoveableResource(const std::string& data) : size_(data.length()) {
data_ = new std::string(data);
std::cout << "Constructor: " << *data_ << std::endl;
}
// Copy constructor
MoveableResource(const MoveableResource& other) : size_(other.size_) {
data_ = new std::string(*other.data_);
std::cout << "Copy constructor: " << *data_ << std::endl;
}
// Copy assignment operator
MoveableResource& operator=(const MoveableResource& other) {
if (this != &other) {
delete data_;
size_ = other.size_;
data_ = new std::string(*other.data_);
std::cout << "Copy assignment: " << *data_ << std::endl;
}
return *this;
}
// Move constructor
MoveableResource(MoveableResource&& other) noexcept : data_(other.data_), size_(other.size_) {
other.data_ = nullptr;
other.size_ = 0;
std::cout << "Move constructor: " << (data_ ? *data_ : "null") << std::endl;
}
// Move assignment operator
MoveableResource& operator=(MoveableResource&& other) noexcept {
if (this != &other) {
delete data_;
data_ = other.data_;
size_ = other.size_;
other.data_ = nullptr;
other.size_ = 0;
std::cout << "Move assignment: " << (data_ ? *data_ : "null") << std::endl;
}
return *this;
}
// Destructor
~MoveableResource() {
if (data_) {
std::cout << "Destructor: " << *data_ << std::endl;
delete data_;
} else {
std::cout << "Destructor: moved-from object" << std::endl;
}
}
// Utility methods
const std::string& getData() const {
return data_ ? *data_ : *new std::string("moved-from");
}
size_t getSize() const { return size_; }
bool isEmpty() const { return data_ == nullptr; }
};
// Factory function returning by value (enables RVO/move)
MoveableResource createResource(const std::string& data) {
return MoveableResource(data);
}
// Function taking rvalue reference
void processRValue(MoveableResource&& resource) {
std::cout << "Processing rvalue: " << resource.getData() << std::endl;
}
// Function taking lvalue reference
void processLValue(const MoveableResource& resource) {
std::cout << "Processing lvalue: " << resource.getData() << std::endl;
}
// Overloaded function for both lvalue and rvalue
void processResource(const MoveableResource& resource) {
std::cout << "Processing lvalue ref: " << resource.getData() << std::endl;
}
void processResource(MoveableResource&& resource) {
std::cout << "Processing rvalue ref: " << resource.getData() << std::endl;
}
void demonstrateBasicMoveSemantics() {
std::cout << "=== Basic Move Semantics ===" << std::endl;
// Constructor
MoveableResource resource1("Original Data");
// Copy constructor
MoveableResource resource2 = resource1;
// Move constructor using std::move
MoveableResource resource3 = std::move(resource1);
std::cout << "After move, resource1 is " << (resource1.isEmpty() ? "empty" : "not empty") << std::endl;
// Copy assignment
MoveableResource resource4("Assignment Target");
resource4 = resource2;
// Move assignment
MoveableResource resource5("Move Assignment Target");
resource5 = std::move(resource2);
std::cout << "After move assignment, resource2 is " << (resource2.isEmpty() ? "empty" : "not empty") << std::endl;
// RVO/NRVO - Return Value Optimization
auto rvo_resource = createResource("RVO Resource");
// Move from temporary
MoveableResource temp_resource = createResource("Temporary");
// Function overload resolution
MoveableResource permanent("Permanent");
processResource(permanent); // Calls lvalue version
processResource(std::move(permanent)); // Calls rvalue version
processResource(MoveableResource("Temporary")); // Calls rvalue version
}
// String class with move semantics
class MyString {
private:
char* data_;
size_t length_;
size_t capacity_;
public:
// Default constructor
MyString() : data_(nullptr), length_(0), capacity_(0) {
std::cout << "MyString default constructor" << std::endl;
}
// Constructor from C-string
MyString(const char* str) {
length_ = strlen(str);
capacity_ = length_ + 1;
data_ = new char[capacity_];
strcpy(data_, str);
std::cout << "MyString constructor: " << data_ << std::endl;
}
// Copy constructor
MyString(const MyString& other) : length_(other.length_), capacity_(other.capacity_) {
if (other.data_) {
data_ = new char[capacity_];
strcpy(data_, other.data_);
std::cout << "MyString copy constructor: " << data_ << std::endl;
} else {
data_ = nullptr;
}
}
// Move constructor
MyString(MyString&& other) noexcept
: data_(other.data_), length_(other.length_), capacity_(other.capacity_) {
other.data_ = nullptr;
other.length_ = 0;
other.capacity_ = 0;
std::cout << "MyString move constructor: " << (data_ ? data_ : "null") << std::endl;
}
// Copy assignment
MyString& operator=(const MyString& other) {
if (this != &other) {
delete[] data_;
length_ = other.length_;
capacity_ = other.capacity_;
if (other.data_) {
data_ = new char[capacity_];
strcpy(data_, other.data_);
std::cout << "MyString copy assignment: " << data_ << std::endl;
} else {
data_ = nullptr;
}
}
return *this;
}
// Move assignment
MyString& operator=(MyString&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
length_ = other.length_;
capacity_ = other.capacity_;
other.data_ = nullptr;
other.length_ = 0;
other.capacity_ = 0;
std::cout << "MyString move assignment: " << (data_ ? data_ : "null") << std::endl;
}
return *this;
}
// Destructor
~MyString() {
if (data_) {
std::cout << "MyString destructor: " << data_ << std::endl;
delete[] data_;
} else {
std::cout << "MyString destructor: moved-from object" << std::endl;
}
}
// Utility methods
const char* c_str() const { return data_ ? data_ : ""; }
size_t length() const { return length_; }
bool empty() const { return data_ == nullptr || length_ == 0; }
// Concatenation with move semantics
MyString operator+(const MyString& other) const {
size_t new_length = length_ + other.length_;
char* new_data = new char[new_length + 1];
if (data_) strcpy(new_data, data_);
else new_data[0] = '\\0';
if (other.data_) strcat(new_data, other.data_);
MyString result;
result.data_ = new_data;
result.length_ = new_length;
result.capacity_ = new_length + 1;
return result; // Move on return
}
MyString& operator+=(const MyString& other) {
if (other.length_ > 0) {
size_t new_length = length_ + other.length_;
if (new_length >= capacity_) {
capacity_ = new_length * 2;
char* new_data = new char[capacity_];
if (data_) {
strcpy(new_data, data_);
delete[] data_;
} else {
new_data[0] = '\\0';
}
data_ = new_data;
}
strcat(data_, other.data_);
length_ = new_length;
}
return *this;
}
};
void demonstrateStringMoveSemantics() {
std::cout << "=== String Move Semantics ===" << std::endl;
MyString str1("Hello");
MyString str2(" World");
// Copy construction
MyString str3 = str1;
// Move construction
MyString str4 = std::move(str2);
std::cout << "str2 after move: '" << str2.c_str() << "'" << std::endl;
// String concatenation
MyString result = str1 + str4; // Creates temporary, then moves
std::cout << "Concatenation result: " << result.c_str() << std::endl;
// Move assignment
MyString final_str("Initial");
final_str = std::move(result);
std::cout << "Final string: " << final_str.c_str() << std::endl;
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_move_semantics_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_move_semantics_project.name
# Expected move semantics classes and functions
expected_entities = [
f"{project_name}.basic_move_semantics.MoveableResource",
f"{project_name}.basic_move_semantics.MyString",
f"{project_name}.basic_move_semantics.createResource",
f"{project_name}.basic_move_semantics.processRValue",
f"{project_name}.basic_move_semantics.demonstrateBasicMoveSemantics",
]
# Get all node creation calls
all_calls = mock_ingestor.ensure_node_batch.call_args_list
class_calls = [call for call in all_calls if call[0][0] == "Class"]
function_calls = [call for call in all_calls if call[0][0] == "Function"]
created_entities = {
call[0][1]["qualified_name"] for call in class_calls + function_calls
}
# Verify expected entities were created
found_entities = [
entity for entity in expected_entities if entity in created_entities
]
assert len(found_entities) >= 4, (
f"Expected at least 4 move semantics entities, found {len(found_entities)}: {found_entities}"
)
def test_perfect_forwarding(
cpp_move_semantics_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test perfect forwarding and universal references."""
test_file = cpp_move_semantics_project / "perfect_forwarding.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <type_traits>
// Simple class for forwarding demonstrations
class ForwardingTarget {
private:
std::string name_;
public:
// Constructor from string
ForwardingTarget(const std::string& name) : name_(name) {
std::cout << "ForwardingTarget copy constructor: " << name_ << std::endl;
}
// Constructor from rvalue string
ForwardingTarget(std::string&& name) : name_(std::move(name)) {
std::cout << "ForwardingTarget move constructor: " << name_ << std::endl;
}
// Copy constructor
ForwardingTarget(const ForwardingTarget& other) : name_(other.name_) {
std::cout << "ForwardingTarget copy from other: " << name_ << std::endl;
}
// Move constructor
ForwardingTarget(ForwardingTarget&& other) noexcept : name_(std::move(other.name_)) {
std::cout << "ForwardingTarget move from other: " << name_ << std::endl;
}
const std::string& getName() const { return name_; }
};
// Perfect forwarding factory
template<typename T, typename... Args>
std::unique_ptr<T> make_unique_perfect(Args&&... args) {
std::cout << "Perfect forwarding factory called" << std::endl;
return std::make_unique<T>(std::forward<Args>(args)...);
}
// Wrapper with perfect forwarding
template<typename T>
class Wrapper {
private:
T wrapped_;
public:
// Perfect forwarding constructor
template<typename U>
Wrapper(U&& value) : wrapped_(std::forward<U>(value)) {
std::cout << "Wrapper perfect forwarding constructor" << std::endl;
}
// Perfect forwarding assignment
template<typename U>
Wrapper& operator=(U&& value) {
wrapped_ = std::forward<U>(value);
std::cout << "Wrapper perfect forwarding assignment" << std::endl;
return *this;
}
const T& get() const { return wrapped_; }
T& get() { return wrapped_; }
};
// Function with universal reference
template<typename T>
void processUniversal(T&& param) {
std::cout << "Universal reference function called" << std::endl;
std::cout << "Type: " << typeid(T).name() << std::endl;
if constexpr (std::is_lvalue_reference_v<T>) {
std::cout << "Received lvalue reference" << std::endl;
} else {
std::cout << "Received rvalue reference" << std::endl;
}
}
// Forwarding function
template<typename T>
void forwardingFunction(T&& param) {
std::cout << "Forwarding function - before forward" << std::endl;
processUniversal(std::forward<T>(param));
std::cout << "Forwarding function - after forward" << std::endl;
}
// Variadic template with perfect forwarding
template<typename Func, typename... Args>
auto invoke_perfect(Func&& func, Args&&... args)
-> decltype(std::forward<Func>(func)(std::forward<Args>(args)...)) {
std::cout << "Perfect forwarding invoke with " << sizeof...(args) << " arguments" << std::endl;
return std::forward<Func>(func)(std::forward<Args>(args)...);
}
// Function object for testing
struct MultiplyBy {
int factor_;
MultiplyBy(int factor) : factor_(factor) {}
int operator()(int value) const {
std::cout << "MultiplyBy called: " << value << " * " << factor_ << std::endl;
return value * factor_;
}
};
void demonstratePerfectForwarding() {
std::cout << "=== Perfect Forwarding ===" << std::endl;
// Perfect forwarding factory
std::string lvalue_str = "LValue String";
auto target1 = make_unique_perfect<ForwardingTarget>(lvalue_str); // Copy
auto target2 = make_unique_perfect<ForwardingTarget>(std::string("RValue String")); // Move
// Wrapper with perfect forwarding
std::string wrapped_str = "Wrapped";
Wrapper<std::string> wrapper1(wrapped_str); // Copy
Wrapper<std::string> wrapper2(std::string("Move Wrapped")); // Move
// Universal reference function
std::string test_str = "Test";
processUniversal(test_str); // Lvalue reference
processUniversal(std::string("Temporary")); // Rvalue reference
processUniversal(std::move(test_str)); // Rvalue reference
// Forwarding chain
std::string forward_str = "Forward Test";
forwardingFunction(forward_str); // Lvalue
forwardingFunction(std::string("Forward Temp")); // Rvalue
// Perfect forwarding with function objects
MultiplyBy multiply_by_3(3);
int result1 = invoke_perfect(multiply_by_3, 5); // Lvalue function object
int result2 = invoke_perfect(MultiplyBy(2), 7); // Rvalue function object
std::cout << "Results: " << result1 << ", " << result2 << std::endl;
// Lambda with perfect forwarding
auto perfect_lambda = [](auto&& func, auto&&... args) {
std::cout << "Lambda perfect forwarding" << std::endl;
return std::forward<decltype(func)>(func)(std::forward<decltype(args)>(args)...);
};
int lambda_result = perfect_lambda(MultiplyBy(4), 3);
std::cout << "Lambda result: " << lambda_result << std::endl;
}
// SFINAE with perfect forwarding
template<typename T>
class SFINAEWrapper {
private:
T value_;
public:
// Enable if T is constructible from Args
template<typename... Args,
typename = std::enable_if_t<std::is_constructible_v<T, Args...>>>
SFINAEWrapper(Args&&... args) : value_(std::forward<Args>(args)...) {
std::cout << "SFINAE wrapper constructed" << std::endl;
}
// Perfect forwarding assignment with SFINAE
template<typename U,
typename = std::enable_if_t<std::is_assignable_v<T&, U>>>
SFINAEWrapper& operator=(U&& other) {
value_ = std::forward<U>(other);
std::cout << "SFINAE assignment" << std::endl;
return *this;
}
const T& get() const { return value_; }
};
// Conditional perfect forwarding
template<typename T>
void conditionalForward(T&& param) {
if constexpr (std::is_same_v<std::decay_t<T>, std::string>) {
std::cout << "String-specific forwarding" << std::endl;
ForwardingTarget target(std::forward<T>(param));
} else {
std::cout << "Generic forwarding for type: " << typeid(T).name() << std::endl;
}
}
void demonstrateAdvancedForwarding() {
std::cout << "=== Advanced Perfect Forwarding ===" << std::endl;
// SFINAE wrapper
SFINAEWrapper<std::string> sfinae_wrapper("SFINAE Test");
std::string assign_str = "Assignment";
sfinae_wrapper = assign_str;
sfinae_wrapper = std::string("Move Assignment");
// Conditional forwarding
std::string cond_str = "Conditional";
conditionalForward(cond_str);
conditionalForward(std::string("Conditional Move"));
conditionalForward(42);
conditionalForward(3.14);
}
// Reference collapsing demonstration
template<typename T>
void demonstrateReferenceCollapsing(T&& param) {
std::cout << "=== Reference Collapsing ===" << std::endl;
// T&& can be either lvalue reference or rvalue reference
using param_type = decltype(param);
std::cout << "Parameter type info:" << std::endl;
std::cout << " Is lvalue reference: " << std::is_lvalue_reference_v<param_type> << std::endl;
std::cout << " Is rvalue reference: " << std::is_rvalue_reference_v<param_type> << std::endl;
std::cout << " Type name: " << typeid(T).name() << std::endl;
// Forward appropriately
ForwardingTarget target(std::forward<T>(param));
}
void testReferenceCollapsing() {
std::string lvalue = "LValue";
std::string& lvalue_ref = lvalue;
// T deduced as std::string&, T&& becomes std::string& (reference collapsing)
demonstrateReferenceCollapsing(lvalue);
demonstrateReferenceCollapsing(lvalue_ref);
// T deduced as std::string, T&& becomes std::string&&
demonstrateReferenceCollapsing(std::string("RValue"));
demonstrateReferenceCollapsing(std::move(lvalue));
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_move_semantics_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_move_semantics_project.name
# Expected perfect forwarding classes and functions
expected_classes = [
f"{project_name}.perfect_forwarding.ForwardingTarget",
f"{project_name}.perfect_forwarding.Wrapper",
f"{project_name}.perfect_forwarding.MultiplyBy",
f"{project_name}.perfect_forwarding.SFINAEWrapper",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify expected classes were created
found_classes = [cls for cls in expected_classes if cls in created_classes]
assert len(found_classes) >= 3, (
f"Expected at least 3 perfect forwarding classes, found {len(found_classes)}: {found_classes}"
)
def test_move_optimization_patterns(
cpp_move_semantics_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test various move optimization patterns and techniques."""
test_file = cpp_move_semantics_project / "move_optimization.cpp"
test_file.write_text(
"""
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <utility>
#include <algorithm>
// Container with move optimizations
template<typename T>
class OptimizedVector {
private:
T* data_;
size_t size_;
size_t capacity_;
void reallocate(size_t new_capacity) {
T* new_data = static_cast<T*>(operator new(new_capacity * sizeof(T)));
if constexpr (std::is_nothrow_move_constructible_v<T>) {
// Use move construction if it's noexcept
for (size_t i = 0; i < size_; ++i) {
new (new_data + i) T(std::move(data_[i]));
data_[i].~T();
}
} else {
// Fall back to copy construction
for (size_t i = 0; i < size_; ++i) {
new (new_data + i) T(data_[i]);
data_[i].~T();
}
}
operator delete(data_);
data_ = new_data;
capacity_ = new_capacity;
}
public:
OptimizedVector() : data_(nullptr), size_(0), capacity_(0) {}
~OptimizedVector() {
for (size_t i = 0; i < size_; ++i) {
data_[i].~T();
}
operator delete(data_);
}
// Move constructor
OptimizedVector(OptimizedVector&& other) noexcept
: data_(other.data_), size_(other.size_), capacity_(other.capacity_) {
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
}
// Move assignment
OptimizedVector& operator=(OptimizedVector&& other) noexcept {
if (this != &other) {
// Destroy current elements
for (size_t i = 0; i < size_; ++i) {
data_[i].~T();
}
operator delete(data_);
// Move from other
data_ = other.data_;
size_ = other.size_;
capacity_ = other.capacity_;
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
}
return *this;
}
// Copy operations (rule of 5)
OptimizedVector(const OptimizedVector& other) : size_(other.size_), capacity_(other.capacity_) {
data_ = static_cast<T*>(operator new(capacity_ * sizeof(T)));
for (size_t i = 0; i < size_; ++i) {
new (data_ + i) T(other.data_[i]);
}
}
OptimizedVector& operator=(const OptimizedVector& other) {
if (this != &other) {
OptimizedVector temp(other);
*this = std::move(temp); // Use move assignment
}
return *this;
}
// Emplace back with perfect forwarding
template<typename... Args>
void emplace_back(Args&&... args) {
if (size_ >= capacity_) {
reallocate(capacity_ == 0 ? 1 : capacity_ * 2);
}
new (data_ + size_) T(std::forward<Args>(args)...);
++size_;
}
// Push back with move semantics
void push_back(const T& value) {
emplace_back(value);
}
void push_back(T&& value) {
emplace_back(std::move(value));
}
// Access
T& operator[](size_t index) { return data_[index]; }
const T& operator[](size_t index) const { return data_[index]; }
size_t size() const { return size_; }
size_t capacity() const { return capacity_; }
// Iterator support for range-based for
T* begin() { return data_; }
T* end() { return data_ + size_; }
const T* begin() const { return data_; }
const T* end() const { return data_ + size_; }
};
// Move-only type
class MoveOnlyResource {
private:
std::unique_ptr<int[]> data_;
size_t size_;
public:
explicit MoveOnlyResource(size_t size) : size_(size) {
data_ = std::make_unique<int[]>(size);
for (size_t i = 0; i < size_; ++i) {
data_[i] = static_cast<int>(i);
}
std::cout << "MoveOnlyResource created with size " << size_ << std::endl;
}
// Move constructor
MoveOnlyResource(MoveOnlyResource&& other) noexcept
: data_(std::move(other.data_)), size_(other.size_) {
other.size_ = 0;
std::cout << "MoveOnlyResource moved (size " << size_ << ")" << std::endl;
}
// Move assignment
MoveOnlyResource& operator=(MoveOnlyResource&& other) noexcept {
if (this != &other) {
data_ = std::move(other.data_);
size_ = other.size_;
other.size_ = 0;
std::cout << "MoveOnlyResource move assigned (size " << size_ << ")" << std::endl;
}
return *this;
}
// Delete copy operations
MoveOnlyResource(const MoveOnlyResource&) = delete;
MoveOnlyResource& operator=(const MoveOnlyResource&) = delete;
size_t size() const { return size_; }
int* getData() const { return data_.get(); }
void process() const {
if (data_) {
std::cout << "Processing " << size_ << " elements" << std::endl;
}
}
};
// Factory functions with move optimizations
MoveOnlyResource createMoveOnlyResource(size_t size) {
return MoveOnlyResource(size); // RVO/NRVO
}
OptimizedVector<std::string> createStringVector() {
OptimizedVector<std::string> vec;
vec.emplace_back("First");
vec.emplace_back("Second");
vec.push_back(std::string("Third"));
return vec; // RVO
}
// Sink function taking by value for optimal performance
void processMoveOnly(MoveOnlyResource resource) {
std::cout << "Processing move-only resource in sink function" << std::endl;
resource.process();
}
// Function returning multiple values using structured bindings and move
std::pair<MoveOnlyResource, OptimizedVector<std::string>>
createMultipleResources() {
auto resource = createMoveOnlyResource(10);
auto vector = createStringVector();
return std::make_pair(std::move(resource), std::move(vector));
}
void demonstrateMoveOptimizations() {
std::cout << "=== Move Optimizations ===" << std::endl;
// Move-only resource
auto resource1 = createMoveOnlyResource(5);
auto resource2 = std::move(resource1);
// Sink function
processMoveOnly(createMoveOnlyResource(3));
processMoveOnly(std::move(resource2));
// Container optimizations
OptimizedVector<std::string> vec;
std::string str1 = "Copy this";
vec.push_back(str1); // Copy
vec.push_back(std::string("Move this")); // Move
vec.emplace_back("Construct in place"); // Direct construction
std::cout << "Vector contents:" << std::endl;
for (const auto& item : vec) {
std::cout << " " << item << std::endl;
}
// Move container
auto vec2 = std::move(vec);
std::cout << "After move - vec size: " << vec.size() << ", vec2 size: " << vec2.size() << std::endl;
// Multiple return values
auto [resource, string_vec] = createMultipleResources();
resource.process();
std::cout << "Returned vector size: " << string_vec.size() << std::endl;
}
// Conditional move based on type traits
template<typename T>
class ConditionalMover {
private:
T value_;
public:
template<typename U>
ConditionalMover(U&& value) : value_(std::forward<U>(value)) {}
// Move if possible, copy otherwise
T extract() {
if constexpr (std::is_move_constructible_v<T>) {
return std::move(value_);
} else {
return value_; // Copy
}
}
// Force move even if potentially throwing
T extract_force_move() {
return std::move(value_);
}
// Safe move - only if noexcept
T extract_safe() {
if constexpr (std::is_nothrow_move_constructible_v<T>) {
return std::move(value_);
} else {
return value_;
}
}
};
// Class with conditional noexcept
class ConditionalNoexcept {
private:
std::string data_;
public:
ConditionalNoexcept(std::string data) : data_(std::move(data)) {}
// Copy constructor
ConditionalNoexcept(const ConditionalNoexcept& other) : data_(other.data_) {}
// Move constructor - noexcept depends on std::string's move constructor
ConditionalNoexcept(ConditionalNoexcept&& other)
noexcept(std::is_nothrow_move_constructible_v<std::string>)
: data_(std::move(other.data_)) {}
// Assignment with strong exception safety
ConditionalNoexcept& operator=(ConditionalNoexcept other) {
// Pass by value, then move
swap(*this, other);
return *this;
}
friend void swap(ConditionalNoexcept& first, ConditionalNoexcept& second) noexcept {
using std::swap;
swap(first.data_, second.data_);
}
const std::string& getData() const { return data_; }
};
void demonstrateConditionalMove() {
std::cout << "=== Conditional Move Semantics ===" << std::endl;
// Test with string (move constructible)
ConditionalMover<std::string> string_mover("Test String");
auto extracted_string = string_mover.extract();
std::cout << "Extracted string: " << extracted_string << std::endl;
// Test with move-only type
ConditionalMover<MoveOnlyResource> resource_mover(createMoveOnlyResource(7));
auto extracted_resource = resource_mover.extract();
extracted_resource.process();
// Conditional noexcept class
ConditionalNoexcept obj1("First");
ConditionalNoexcept obj2("Second");
std::cout << "Before swap: obj1=" << obj1.getData() << ", obj2=" << obj2.getData() << std::endl;
swap(obj1, obj2);
std::cout << "After swap: obj1=" << obj1.getData() << ", obj2=" << obj2.getData() << std::endl;
}
// Algorithm with move optimization
template<typename Iterator>
void move_elements(Iterator first, Iterator last, Iterator dest) {
while (first != last) {
*dest = std::move(*first);
++first;
++dest;
}
}
// Custom swap with move semantics
template<typename T>
void optimized_swap(T& a, T& b) noexcept(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_move_assignable_v<T>) {
T temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}
void demonstrateAlgorithmOptimizations() {
std::cout << "=== Algorithm Move Optimizations ===" << std::endl;
// Vector of move-only resources
std::vector<MoveOnlyResource> resources;
resources.push_back(createMoveOnlyResource(1));
resources.push_back(createMoveOnlyResource(2));
resources.push_back(createMoveOnlyResource(3));