When to pass by value, reference or pointer in C++?
| Case | Use |
|---|---|
| Small type (int, double, pointer) | T by value |
| Big object, only read | const T& |
| Function must change the argument | T& |
| Argument may be missing | T* (or std::optional) |
| Function keeps its own copy | T by value, then std::move |
| Read only text | std::string_view |
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
void a(int n) { std::cout << "value " << n << '\n'; }
void b(const std::vector<int>& v) { std::cout << "const ref " << v.size() << '\n'; }
void c(int& n) { n++; }
void d(const int* p) { std::cout << (p ? "pointer set" : "no value") << '\n'; }
void e(std::string_view s) { std::cout << "view " << s << '\n'; }
int main() {
int n = 1;
a(n);
b({1, 2, 3});
c(n);
d(&n);
d(nullptr);
e("text");
std::cout << n << '\n';
}
Output
value 1
const ref 3
pointer set
no value
view text
2
See References and Pointers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |