Skip to content

Raw pointers

Raw pointers

A pointer is a type of variable. It stores the address of an object in memory, and is used to access that object. A raw pointer is a pointer whose lifetime isn't controlled by an encapsulating object, such as a smart pointer.

Raw pointers might be dangerous. Try to avoid them.

1
int *x = new int(5);

1
std::cout << "x: " << x << '\n';

1
2
3
4
5
if (x) {
    std::cout << "*x: " << *x << '\n';
} else {
    std::cout << "*x: empty" << '\n';
}

1
2
3
4
5
// - Forgetting to delete causes memory leaks
// - Forgetting to update to nullptr might lead to segmentation faults
// - Use smart pointers to delete the data automatically
delete x;
x = nullptr;

1
2
3
4
5
6
7
8
// - This is what existed before vectors
// - Point to a sequence of values
// - Always use vectors instead of this
// - If you need to access the raw data, use vector::data()
int *x2 = new int[10];
for (int i2 = 0; i2 < 10; ++i2) {
    x2[i2] = 10 + i2 * 10;
}

1
2
3
std::cout << "x2: " << x2 << '\n';
std::cout << "&x2[0]: " << &x2[0] << '\n';
std::cout << "x2[0]: " << x2[0] << '\n';

1
2
3
std::cout << "*x2: " << *x2 << '\n';
std::cout << "x2[3]: " << x2[3] << '\n';
std::cout << "*(x2+3): " << *(x2 + 3) << '\n';

1
2
3
// - Slightly different command: more danger
delete[] x2;
x2 = nullptr;

Share Snippets