Practical Code Patterns
Reference Passing Patterns in Real-World Scenarios
std::vector<int> transformVector(const std::vector<int>& input) {
std::vector<int> result;
for (const auto& value : input) {
result.push_back(value * 2);
}
return result;
}
2. Algorithm Implementation
template <typename Container>
void sortContainer(Container& container) {
std::sort(container.begin(), container.end());
}
Reference Handling Strategies
graph TD
A[Reference Passing] --> B[Const Reference]
A --> C[Non-Const Reference]
A --> D[Universal Reference]
B --> E[Read-Only Access]
C --> F[Modification Allowed]
D --> G[Flexible Handling]
Advanced Reference Patterns
Range-Based Processing
template <typename Container>
void processContainer(const Container& container) {
for (const auto& item : container) {
// Process each item
std::cout << item << " ";
}
}
Pattern |
Description |
Use Case |
Const Reference |
Prevents modification |
Read-only operations |
Reference Wrapper |
Creates reference-like objects |
Storing references in containers |
Perfect Forwarding |
Preserves value category |
Template metaprogramming |
Reference Wrapper Example
#include <functional>
#include <vector>
void referenceWrapperDemo() {
int x = 10, y = 20, z = 30;
std::vector<std::reference_wrapper<int>> refs{x, y, z};
for (auto& ref : refs) {
ref.get() *= 2;
}
}
Error Handling with References
std::optional<std::reference_wrapper<int>>
findElement(std::vector<int>& vec, int target) {
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
return std::ref(*it);
}
return std::nullopt;
}
Practical Considerations in LabEx Environments
- Minimize unnecessary copying
- Use const references for input parameters
- Leverage template techniques for generic programming
Complex Object Handling
class DataProcessor {
public:
void processData(const std::vector<ComplexObject>& data) {
for (const auto& item : data) {
// Efficient processing without copying
processItem(item);
}
}
private:
void processItem(const ComplexObject& item) {
// Complex object processing logic
}
};
Best Practices
- Always consider the performance impact of reference passing
- Use const references for read-only operations
- Employ universal references for maximum flexibility
- Be mindful of lifetime management when using references