Coding Techniques
References: lvalue and rvalue · Study material
Sink parameters: take by value, then std::move
When a function stores its argument, take it by value and move it into place. Callers passing an lvalue pay one copy; callers passing a temporary pay only moves – one function covers both cases. Return members as const references to avoid copies.
#include <iostream>
#include <string>
#include <utility>
class Employee {
std::string name_;
public:
explicit Employee(std::string name) : name_(std::move(name)) {} // take by value, then move into place
const std::string& name() const { return name_; } // return a const reference to a member
};
int main() {
std::string n = "Kavya Iyer";
Employee a(n); // one copy (into the parameter), then a move
Employee b(std::string("Arjun")); // only moves
std::cout << a.name() << " | " << b.name() << " | " << n << '\n';
return 0;
}
Kavya Iyer | Arjun | Kavya Iyer
Choose the parameter type by intent
| Intent | Parameter |
|---|---|
| read a small value | int x |
| read a large object | const T& x |
| modify the caller's object | T& x |
| keep a copy / take ownership | T x then std::move(x) |
| optional object | T* x or std::optional<T> |
| forward anything (templates) | T&& x + std::forward<T>(x) |
Write a perfect-forwarding factory
#include <memory>
#include <utility>
template <typename T, typename... Args>
std::unique_ptr<T> make(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); // what std::make_unique does
}
auto p = make<std::string>(5, '*'); // forwards 5 and '*' to std::string's constructor Avoid dangling references from containers
std::vector<std::string> names{"a", "b"};
std::string& first = names.front();
names.push_back("c"); // may reallocate: first is now dangling
std::cout << first; // undefined behaviour
// Safe: keep an index, or re-read after modifying
std::size_t idx = 0;
names.push_back("d");
std::cout << names[idx]; Good reference habits
- Pass large read-only objects as
const T&. - Use
T¶meters only when the function really modifies the argument. - Return references only to objects that outlive the call.
- Use
const auto&in range-for loops unless you need copies or changes. - Apply
std::moveonly to objects you will not read again. - Use
std::forwardexactly once per forwarding reference.