简体   繁体   中英

Guarantee Unique objects in factory using unique_ptr

I came across the following code for a factory.

  • T::create(std::forward<Args>(args)...) returns a pointer to an object created dynamically. So basically if two objects have the same address then they are the same.
  • unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr.

#pragma once

#include <memory>
#include <vector>

template <typename T>
class PoolFactory {
 public:
  template <typename... Args>
  T *getInstance(Args... args) {
    _createdItems.push_back(
        std::unique_ptr<T>(T::create(std::forward<Args>(args)...)));
    return _createdItems.back().get();
  }
  ~PoolFactory() = default;

 public:
  std::vector<std::unique_ptr<T>> _createdItems;
};

Question

Suppose we are trying to insert an object that already exists in the vector. Since we are using a factory and IF the object already exists we just want to retrieve it. How will that archtitecture that contains move semantics guarantee that behavior?

Interpreting this code, in this factory your objects are identified by getInstance arguments. The interface also suggests that the callers know both T and its constructor arguments, so that they can construct T themselves.

The only use for this factory is to make each object a singleton.

You need a mapping (args...) -> object , rather than an array, so that first you look up an existing object using args... and create the object if it doesn't exist yet.

You've gotten the "uniqueness" of std::unique_ptr<T> backwards. There is not a magic mechanism such that when you create a std::unique_ptr<T> somehow it checks all the currently existing std::unique_ptr<T> and does something different if one owns the same pointer value.

Instead, it is assumed that you have previously new ed a T * and construct a std::unique_ptr<T> from it, or call std::make_unique<T> to new a T and wrap it in a unique_ptr<T> for you. If that assumption is not the case, and the std::unique_ptr<T> is destroyed, your program's behaviour is undefined.

The prohibition on copying then assures you that delete is called exactly once , and often with no additional effort on your part (ie the pointee's lifetime is exactly the same as the pointer's lifetime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM