Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Unique Objects

I would like to create a class where the possible universe of instances is limited, and of which users cannot create new instances. For example, currencies are unique, and users of the library I am working should not be able to create new currencies, or copy existing ones. It is kind of like a multiple-ton pattern, I guess. What I have so far is:

#include <string>
#include <boost/smart_ptr/shared_ptr.hpp>

struct Currency {
public:
    typedef const Currency * Pointer;

    std::string code;

    static const Currency & Get(const std::string & Code);
private:
    Currency();
    Currency(const std::string & c);
};

Currency::Currency(const std::string & c)
:code(c) {}

const Currency & Currency::Get(const std::string & Code) {
    typedef boost::shared_ptr<Currency> Value;
    typedef std::map<std::string, Value> MapType;
    static std::map<std::string, Value> map_;

    if (map_.empty()) {
        // Initialize your map here, from a database query or what have you...
    }
    MapType::const_iterator it = map_.find(Code);
    if (it == map_.end()) {
        throw std::exception(("[Currency::Get] Currency '" + Code + "' not found").c_str());
    }
    return *it->second;
}

Are there any obvious problems with this design? (I know that this isn't thread-safe) Is there a generally accepted technique/pattern that I am not aware of that is traditionally used to achieve this?

Thanks, Marc.

like image 615
Paschover Avatar asked Aug 30 '26 12:08

Paschover


1 Answers

Look into boost:noncopyable to prevent copying; that's a good reference solution that you can both trust and learn from. Preventing instantiation is easy: a private constructor.

like image 156
Jon Avatar answered Sep 02 '26 05:09

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!