Memory Ownership and Smart Pointers

Returning Unique Pointers from Functions

What's the best way to return a unique pointer from a function?

Abstract art representing computer programming

Returning a std::unique_ptr from a function is a great way to transfer ownership of dynamically allocated objects. It's both efficient and safe, as it clearly communicates the ownership transfer to the caller. Here are some best practices for returning unique_ptr from functions:

1. Return by Value

The most straightforward and recommended way is to return the unique_ptr by value:

#include <memory>
#include <string>

class Character {
public:
  std::string Name;
};

std::unique_ptr<Character> CreateCharacter(
  const std::string& Name
) {
  return std::make_unique<Character>(Name); 
}

int main() {
  auto Frodo{CreateCharacter("Frodo")};
  // Frodo now owns the Character object
}

This approach is efficient because of return value optimization (RVO) and move semantics in modern C++.

2. Use std::make_unique()

As shown above, prefer using std::make_unique() to create the unique_ptr. It's more exception-safe and can be more efficient than manually calling new.

3. Avoid Naked new

Try to avoid using naked new in your function. If you must, wrap it immediately in a unique_ptr:

#include <memory>
#include <string>

class Character {
 public:
  std::string Name;
};

std::unique_ptr<Character> CreateComplexCharacter(
  /*...*/
) {
  Character* RawPtr{new Character("Gandalf")};
  // Do some complex initialization...
  return std::unique_ptr<Character>(RawPtr); 
}

4. Return nullptr When Appropriate

If your function might fail to create an object, returning a nullptr unique_ptr is a valid way to signal this:

#include <iostream>
#include <memory>
#include <string>

class Character {
public:
  std::string Name;
};

std::unique_ptr<Character> TryCreateCharacter(
  const std::string& Name
) {
  if (Name.empty()) {
    return nullptr; 
  }
  return std::make_unique<Character>(Name);
}

int main() {
  auto MaybeCharacter{TryCreateCharacter("")};
  if (MaybeCharacter) {
    std::cout << "Character created: "
        << MaybeCharacter->Name;
  } else {
    std::cout << "Failed to create character";
  }
}
Failed to create character

5. Consider Returning by std::unique_ptr&&

In some cases, you might want to return an rvalue reference to a unique_ptr:

#include <memory>
#include <string>
#include <iostream>

class Character {
public:
  std::string Name;
};

std::unique_ptr<Character>&& CreateCharacterRef(
  const std::string& name
) {
  static std::unique_ptr<Character> character{
    new Character(name)
  };

  // Re-initialize the static unique_ptr
  character.reset(new Character(name));

  // Return an rvalue reference
  return std::move(character); 
}

int main() {
  std::unique_ptr<Character> character =
    CreateCharacterRef("John Doe");

  if (character) {
    std::cout << "Character Name: "
    << character->Name;
  }
}
Character Name: John Doe

This can be useful in specific scenarios, but be cautious as it can lead to dangling references if not used correctly.

Remember, when you return a unique_ptr, you're transferring ownership to the caller. The caller becomes responsible for the lifetime of the object. This ownership transfer is clear and explicit, which is one of the main advantages of using unique_ptr.

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

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:

  • 59 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