Dangling Pointers and References

Alternatives to Returning Pointers

What are some alternatives to returning pointers or references from functions?

Abstract art representing computer programming

Returning pointers or references from functions can lead to dangling pointer issues if not handled carefully. Fortunately, C++ provides several safer alternatives. Let's explore some of these options:

1. Return by Value

The simplest and often safest approach is to return objects by value:

#include <string>
#include <iostream>

std::string createGreeting(
  const std::string& name
){
  return "Hello, " + name + "!";
}

int main(){
  std::string greeting =
    createGreeting("Alice");
  std::cout << greeting;
}
Hello, Alice!

Modern C++ compilers are good at optimizing this, often using Return Value Optimization (RVO) to avoid unnecessary copies.

2. Optional Types

When you need to represent the possibility of no value, use std::optional:

#include <optional>
#include <string>
#include <iostream>

std::optional<std::string> findUser(int id) {
  if (id == 1) { return "Alice"; }
  return std::nullopt;
}

int main() {
  auto user = findUser(1);
  if (user) {
    std::cout << "Found user: " << *user << '\n';
  } else { std::cout << "User not found\n"; }
}
Found user: Alice

3. Smart Pointers

When dynamic allocation is necessary, use smart pointers:

#include <memory>
#include <iostream>

std::unique_ptr<int> createNumber() {
  return std::make_unique<int>(42);
}

int main() {
  auto ptr = createNumber();
  std::cout << "The number is: " << *ptr;
}
The number is: 42

std::unique_ptr ensures the object is properly deleted when it's no longer needed.

4. Output Parameters

You can use output parameters to return multiple values:

#include <iostream>

void getMinMax(
  const int* arr, size_t size,
  int& min, int& max
){
  if (size == 0) return;
  min = max = arr[0];
  for (size_t i = 1; i < size; ++i) {
    if (arr[i] < min) min = arr[i];
    if (arr[i] > max) max = arr[i];
  }
}

int main(){
  int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
  int min, max;
  getMinMax(arr, std::size(arr), min, max);
  std::cout << "Min: " << min << ", Max: "
    << max;
}
Min: 1, Max: 9

5. Structured Binding (C++17)

Structured binding allows you to return multiple values easily:

#include <tuple>
#include <iostream>

std::tuple<int, int> getMinMax(
  const int* arr, size_t size
){
  if (size == 0) return {0, 0};
  int min = arr[0], max = arr[0];
  for (size_t i = 1; i < size; ++i) {
    if (arr[i] < min) min = arr[i];
    if (arr[i] > max) max = arr[i];
  }
  return {min, max};
}

int main(){
  int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
  auto [min, max] = getMinMax(
    arr, std::size(arr));
  std::cout << "Min: " << min << ", Max: "
    << max;
}
Min: 1, Max: 9

6. std::pair or std::tuple

For returning two or more values:

#include <utility>
#include <string>
#include <iostream>

std::pair<std::string, int> getNameAndAge(){
  return {"Alice", 30};
}

int main(){
  auto [name, age] = getNameAndAge();
  std::cout << name << " is " << age <<
    " years old";
}
Alice is 30 years old

These alternatives provide safer and more expressive ways to return data from functions without risking dangling pointers. Choose the most appropriate option based on your specific use case and the semantics you want to convey.

This Question is from the Lesson:

Dangling Pointers and References

Learn about an important consideration when returning pointers and references from functions

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Dangling Pointers and References

Learn about an important consideration when returning pointers and references from functions

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 57 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved