【问题标题】:How can I reduce the number of call to constructors in my two classes?如何减少在我的两个类中调用构造函数的次数?
【发布时间】:2020-10-22 19:42:50
【问题描述】:

我正在编写一个Cache 类,它充当std::unordered_map 的扩展,它计算引用并自动删除没有引用的条目。它还有一个布尔参数,让开发人员选择是否要在地图中保留条目,即使没有引用。 此类以CacheRef 实例的形式返回值。以下是上述类的定义:

#pragma once

#include <iostream>
#include <unordered_map>
#include <tuple>
#include <string>
#include <utility>

template <typename TKey, typename TValue>
class Cache;

template <typename TKey, typename TValue>
class CacheRef
{
private:
    using CacheMap = std::unordered_map<TKey, std::tuple<TValue, int, bool>>;
public:
    TValue* value = nullptr;
    
    CacheRef<TKey, TValue>& operator=(const CacheRef<TKey, TValue>&) = delete;
    CacheRef<TKey, TValue>& operator=(CacheRef<TKey, TValue>&& other) = delete;
    CacheRef(const CacheRef<TKey, TValue>& ref) :
    m_validRef(ref.m_validRef), m_valueLocation(ref.m_valueLocation), m_cache(ref.m_cache)
    {
        std::cout << "Reference constructor called" << std::endl;
        initialize();
    }

    CacheRef(CacheRef<TKey, TValue>&& ref) :
    m_validRef(ref.m_validRef), m_valueLocation(ref.m_valueLocation), m_cache(ref.m_cache)
    {
        std::cout << "Move constructor called" << std::endl;
        initialize();
    }

    CacheRef(typename CacheMap::iterator valueLocation, Cache<TKey, TValue>* cache, bool validRef = true)
        : m_valueLocation(valueLocation), m_cache(cache), m_validRef(validRef)
    {
        std::cout << "Normal constructor called" << std::endl;
        initialize();
    }

    ~CacheRef()
    {
        std::cout << "Destructor called" << std::endl;
        if (m_validRef)
        {
            m_cache->deleteReference(m_valueLocation);
        }
    }

private:
    void initialize()
    {
        if (m_validRef)
        {
            value = &std::get<0>(m_valueLocation->second);
            ++std::get<1>(m_valueLocation->second);
        }
    }
    typename CacheMap::iterator m_valueLocation;
    const bool m_validRef;
    Cache<TKey, TValue>* const m_cache;
};

template <typename TKey, typename TValue>
class Cache
{
    using ValueInfo = std::tuple<TValue, int, bool>;
    using CacheMap = std::unordered_map<TKey, ValueInfo>;
public:
    Cache() = default;
    ~Cache() = default;
    CacheRef<TKey, TValue> add(const TKey& key, const TValue& value, bool autoCacheDelete = true)
    {
        // Make sure TValue is not in the cache already
        auto pair = find(key);
        if (pair.second)
        {
            return pair.first;
        }
        else
        {
            // Insert in cache map
            ValueInfo val(value, 0, autoCacheDelete);
            std::pair<typename CacheMap::iterator, bool> insert = m_cache.insert(std::make_pair(key, val));
                
            // Return the newly inserted element as a CacheRef
            return CacheRef<TKey, TValue>(insert.first, this, true);
        }
    }
    
    std::pair<CacheRef<TKey, TValue>, bool> find(const TKey& key)
    {
        typename CacheMap::iterator kvp = m_cache.find(key);
        if (kvp == m_cache.end())
        {
            return std::pair<CacheRef<TKey, TValue>, bool>(CacheRef<TKey, TValue>(kvp, this, false), false);
        }
        else
        {
            return std::pair<CacheRef<TKey, TValue>, bool>(CacheRef<TKey, TValue>(kvp, this, true), true);
        }
    }

    void print()
    {
        for (auto element : m_cache)
        {
            std::cout << "Key: " << element.first << "\tValue:" << std::get<0>(element.second) << " #Ref: " << std::get<1>(element.second) << std::endl;
        }

        std::cout << std::endl;
    }
        
    void deleteReference(typename CacheMap::iterator where)
    {
        int& numRef = std::get<1>(where->second);
        --numRef;
        if (numRef == 0 && std::get<2>(where->second))
        {
            m_cache.erase(where);
        }
    }

private:
    CacheMap m_cache;
};

这是运行的测试函数

int main()
{
    Cache<std::string, int> testCache;
    auto ref = testCache.add("myKey", 10);
    testCache.print();
}

这是输出

> Normal constructor called //<-- This is an invalid reference being created by Cache::find() called by Cache::add() to check if data already exists
> Move constructor called //<-- Probably called by std::pair constructor from Cache::find()
> Destructor called //<-- First data being destroyed
> Normal constructor called //<-- Real data is created by Cache::add()
> Destructor called //<-- Destroyed the return value of Cache::find() when leaving Cache::add() scope
> Key: myKey    Value:10 #Ref: 1

所以我想可以进行一些明显的优化。我首先想到的是在add() 中删除对find() 的调用,但这需要我对如何使用该类更加谨慎,所以我宁愿避免这种情况。

创建一个无效的引用也需要两次构造函数调用,只是为了丢弃我认为不是很干净的实例。实际上,无效引用的整个想法有点困扰我,但当find() 找不到匹配项时,我想不出任何其他返回值

【问题讨论】:

  • 您在构建应用程序时使用了哪些编译器选项?您是否在编译构建命令中启用了优化?
  • 一种方法是add 不打电话给你的find,而是直接打电话给m_cache.find(key);。

标签: c++ oop constructor


【解决方案1】:

老问题,我正在挖掘。我会使用std::optional 作为find 的返回类型。因此您不会生成临时对象:

#include <iostream>
#include <unordered_map>
#include <optional>

template <typename TValue>
struct ValueInfo {
    TValue value;
    int refCount;
    bool autoCacheDelete;
};

template <typename TKey, typename TValue>
class Cache;

template <typename TKey, typename TValue>
class CacheRef
{
private:
    using CacheMap = std::unordered_map<TKey, ValueInfo<TValue>>;
    using CacheMapIterator = CacheMap::iterator;
    TValue* value = nullptr;
public:
    CacheRef& operator=(CacheRef const&) = delete;
    CacheRef& operator=(CacheRef&&) = delete;

    CacheRef(CacheRef const& ref)
    : _validRef(ref._validRef), _valueLocation(ref._valueLocation), _cache(ref._cache)
    {
        std::cout << "Reference constructor called\n";
        initialize();
    }

    CacheRef(CacheRef&& ref)
    : _validRef(ref._validRef), _valueLocation(ref._valueLocation), _cache(ref._cache)
    {
        std::cout << "Move constructor called\n";
        initialize();
    }

    CacheRef(CacheMapIterator valueLocation, Cache<TKey, TValue>* cache, bool validRef = true)
    : _valueLocation(valueLocation), _cache(cache), _validRef(validRef)
    {
        std::cout << "Normal constructor called\n";
        initialize();
    }

    ~CacheRef()
    {
        std::cout << "Destructor called\n";
        if (_validRef)
        {
            _cache->deleteReference(_valueLocation);
        }
    }

private:
    void initialize()
    {
        if (_validRef)
        {
            value = &_valueLocation->second.value;
            ++_valueLocation->second.refCount;
        }
    }
    CacheMapIterator _valueLocation;
    const bool _validRef;
    Cache<TKey, TValue>* const _cache;
};

template <typename TKey, typename TValue>
class Cache
{
private:
    using CacheMap = std::unordered_map<TKey, ValueInfo<TValue>>;
    using CacheMapIterator = CacheMap::iterator;
public:
    Cache() = default;

    CacheRef<TKey, TValue> add(const TKey& key, const TValue& value, bool autoCacheDelete = true)
    {
        // Make sure TValue is not in the cache already
        auto cacheRef = find(key);
        if (cacheRef.has_value()) return cacheRef.value();
        else {
            // Insert in cache map
            ValueInfo val(value, 0, autoCacheDelete);
            auto [iterator, succeeded] = _cache.insert(std::make_pair(key, val));
            // should prolly check 'succeeded'
            // Return the newly inserted element as a CacheRef
            return CacheRef<TKey, TValue>(iterator, this, true);
        }
    }
    
    std::optional<CacheRef<TKey, TValue>> find(const TKey& key)
    {
        auto cacheIt = _cache.find(key);
        if (cacheIt == _cache.end()) return std::nullopt;
        return CacheRef<TKey, TValue>(cacheIt, this, true);
    }

    void print()
    {
        for (auto const& [key, cacheRef] : _cache)
        {
            std::cout << "Key: " << key << "\tValue:" << cacheRef.value << " #Ref: " << cacheRef.refCount << '\n';
        }
    }
        
    void deleteReference(CacheMapIterator where)
    {
        int& numRef = where->second.refCount;
        --numRef;
        if (numRef == 0 && where->second.autoCacheDelete)
        {
            _cache.erase(where);
        }
    }

private:
    CacheMap _cache;
};

int main()
{
    Cache<std::string, int> testCache;
    auto ref = testCache.add("myKey", 10);
    testCache.print();
}

给予:

Normal constructor called
Key: myKey  Value:10 #Ref: 1
Destructor called

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多