Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Performance Considerations With Smart Pointers | Advanced topics
C++ Smart Pointers
course content

Contenido del Curso

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

book
Performance Considerations With Smart Pointers

Smart pointer overhead

Smart pointers introduce some overhead compared to raw pointers, mainly due to their additional functionalities like reference counting or deletion tracking. Even though this overhead is often negligible, as performance-oriented developers, it's important to be aware of potential performance implications.

Example

Suppose you are working on a legacy embedded application that uses thousands of raw pointers. If you replace all these raw pointers with shared pointers, you may observe a noticeable impact in application throughput.

A better approach would be to slowly refactor your code, measuring performance after each iteration, and choosing a combination of shared and unique pointers based on the use case and applicability.

Minimize shared pointer overhead

Shared pointers are more expensive due to their reference counting mechanism. They increase the reference count whenever a copy is made and decrease it when the pointer goes out of scope or gets reset. This can affect performance, especially in high-frequency scenarios or when using a large number of shared pointers.

The solution is to avoid making unnecessary copies of shared pointers and to only use shared pointers when unique pointers can’t cater to your use case.

Benchmark and profile

Regularly benchmark and profile code segments that use smart pointers to identify bottlenecks and optimize performance. You can use tools like Google Benchmark or Valgrind for this purpose.

Which smart pointer should you use if there’s only one resource to be managed, but the resource will be accessed by multiple classes in your code?

Which smart pointer should you use if there’s only one resource to be managed, but the resource will be accessed by multiple classes in your code?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 6. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt