cocos2d-x3.0中数据类型vector,map和value的分析和挖掘

来源:互联网 发布:layout是什么软件 编辑:程序博客网 时间:2024/04/28 08:59

在3.0中,已经不再使用以前的ccarray,ccdictionary,ccint等从以前的oc继承过来的数据类型,转而加入了自己的数据结构,更加符合c++的开发习惯和思考模式,其中就包括了vector,map和value这三种。今天刚好自己研究了相关的源代码,可以结合分析下。

vector就相当于以前的ccarray,对c++的vector做了适当的包装,在一些赋值,释放等相关操作加入了引用计数相关的内存释放操作,使得我们在使用不再需要自己添加retain,release,autorelease等方法。

首先来看vector,新的vector在ccvector.h头文件中定义,包含了如下的方法和成员,需要注意到在c++的vector的基础上,cocos2d-x的vector加入了对内存的控制。


源代码如下:

/****************************************************************************Copyright (c) 2010 ForzeField Studios S.L. http://forzefield.comCopyright (c) 2010-2012 cocos2d-x.orgCopyright (c) 2013-2014 Chukong Technologieshttp://www.cocos2d-x.orgPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.****************************************************************************/#ifndef __CCVECTOR_H__#define __CCVECTOR_H__#include "ccMacros.h"#include "CCRef.h"#include <vector>#include <functional>#include <algorithm> // for std::findNS_CC_BEGINtemplate<class T>class CC_DLL Vector{public:    // ------------------------------------------    // Iterators    // ------------------------------------------    typedef typename std::vector<T>::iterator iterator;    typedef typename std::vector<T>::const_iterator const_iterator;        typedef typename std::vector<T>::reverse_iterator reverse_iterator;    typedef typename std::vector<T>::const_reverse_iterator const_reverse_iterator;        iterator begin() { return _data.begin(); }    const_iterator begin() const { return _data.begin(); }        iterator end() { return _data.end(); }    const_iterator end() const { return _data.end(); }        const_iterator cbegin() const { return _data.cbegin(); }    const_iterator cend() const { return _data.cend(); }        reverse_iterator rbegin() { return _data.rbegin(); }    const_reverse_iterator rbegin() const { return _data.rbegin(); }        reverse_iterator rend() { return _data.rend(); }    const_reverse_iterator rend() const { return _data.rend(); }        const_reverse_iterator crbegin() const { return _data.crbegin(); }    const_reverse_iterator crend() const { return _data.crend(); }        /** Constructor */    Vector<T>()    : _data()    {        static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");    }        /** Constructor with a capacity */    explicit Vector<T>(ssize_t capacity)    : _data()    {        static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");        CCLOGINFO("In the default constructor with capacity of Vector.");        reserve(capacity);    }    /** Destructor */    ~Vector<T>()    {        CCLOGINFO("In the destructor of Vector.");        clear();    }    /** Copy constructor */    Vector<T>(const Vector<T>& other)    {        static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");        CCLOGINFO("In the copy constructor!");        _data = other._data;        addRefForAllObjects();    }        /** Move constructor */    Vector<T>(Vector<T>&& other)    {        static_assert(std::is_convertible<T, Ref*>::value, "Invalid Type for cocos2d::Vector<T>!");        CCLOGINFO("In the move constructor of Vector!");        _data = std::move(other._data);    }        /** Copy assignment operator */    Vector<T>& operator=(const Vector<T>& other)    {        if (this != &other) {            CCLOGINFO("In the copy assignment operator!");            clear();            _data = other._data;            addRefForAllObjects();        }        return *this;    }        /** Move assignment operator */    Vector<T>& operator=(Vector<T>&& other)    {        if (this != &other) {            CCLOGINFO("In the move assignment operator!");            clear();            _data = std::move(other._data);        }        return *this;    }    // Don't uses operator since we could not decide whether it needs 'retain'/'release'.//    T& operator[](int index)//    {//        return _data[index];//    }//    //    const T& operator[](int index) const//    {//        return _data[index];//    }        /** @brief Request a change in capacity      *  @param capacity Minimum capacity for the vector.     *         If n is greater than the current vector capacity,      *         the function causes the container to reallocate its storage increasing its capacity to n (or greater).     */    void reserve(ssize_t n)    {        _data.reserve(n);    }        /** @brief Returns the size of the storage space currently allocated for the vector, expressed in terms of elements.     *  @note This capacity is not necessarily equal to the vector size.      *        It can be equal or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion.     *  @return The size of the currently allocated storage capacity in the vector, measured in terms of the number elements it can hold.     */    ssize_t capacity() const    {        return _data.capacity();    }        /** @brief Returns the number of elements in the vector.     *  @note This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.     *  @return The number of elements in the container.     */    ssize_t size() const    {        return  _data.size();    }        /** @brief Returns whether the vector is empty (i.e. whether its size is 0).     *  @note This function does not modify the container in any way. To clear the content of a vector, see Vector<T>::clear.     */    bool empty() const    {        return _data.empty();    }        /** Returns the maximum number of elements that the vector can hold. */    ssize_t max_size() const    {        return _data.max_size();    }        /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */    ssize_t getIndex(T object) const    {        auto iter = std::find(_data.begin(), _data.end(), object);        if (iter != _data.end())            return iter - _data.begin();        return -1;    }    /** @brief Find the object in the vector.     *  @return Returns an iterator to the first element in the range [first,last) that compares equal to val.      *          If no such element is found, the function returns last.     */    const_iterator find(T object) const    {        return std::find(_data.begin(), _data.end(), object);    }        iterator find(T object)    {        return std::find(_data.begin(), _data.end(), object);    }        /** Returns the element at position 'index' in the vector. */    T at(ssize_t index) const    {        CCASSERT( index >= 0 && index < size(), "index out of range in getObjectAtIndex()");        return _data[index];    }    /** Returns the first element in the vector. */    T front() const    {        return _data.front();    }        /** Returns the last element of the vector. */    T back() const    {        return _data.back();    }    /** Returns a random element of the vector. */    T getRandomObject() const    {        if (!_data.empty())        {            ssize_t randIdx = rand() % _data.size();            return *(_data.begin() + randIdx);        }        return nullptr;    }    /** Returns a Boolean value that indicates whether object is present in vector. */    bool contains(T object) const    {        return( std::find(_data.begin(), _data.end(), object) != _data.end() );    }    /** Returns true if the two vectors are equal */    bool equals(const Vector<T> &other)    {        ssize_t s = this->size();        if (s != other.size())            return false;                for (ssize_t i = 0; i < s; i++)        {            if (this->at(i) != other.at(i))            {                return false;            }        }        return true;    }    // Adds objects        /** @brief Adds a new element at the end of the vector, after its current last element.     *  @note This effectively increases the container size by one,     *        which causes an automatic reallocation of the allocated storage space      *        if -and only if- the new vector size surpasses the current vector capacity.     */    void pushBack(T object)    {        CCASSERT(object != nullptr, "The object should not be nullptr");        _data.push_back( object );        object->retain();    }        /** Push all elements of an existing vector to the end of current vector. */    void pushBack(const Vector<T>& other)    {        for(const auto &obj : other) {            _data.push_back(obj);            obj->retain();        }    }    /** @brief Insert a certain object at a certain index      *  @note The vector is extended by inserting new elements before the element at the specified 'index',     *        effectively increasing the container size by the number of elements inserted.     *        This causes an automatic reallocation of the allocated storage space      *        if -and only if- the new vector size surpasses the current vector capacity.     */    void insert(ssize_t index, T object)    {        CCASSERT(index >= 0 && index <= size(), "Invalid index!");        CCASSERT(object != nullptr, "The object should not be nullptr");        _data.insert((std::begin(_data) + index), object);        object->retain();    }        // Removes Objects    /** Removes the last element in the vector,      *  effectively reducing the container size by one, decrease the referece count of the deleted object.     */    void popBack()    {        CCASSERT(!_data.empty(), "no objects added");        auto last = _data.back();        _data.pop_back();        last->release();    }        /** @brief Remove a certain object in Vector.     *  @param object The object to be removed.     *  @param removeAll Whether to remove all elements with the same value.     *                   If its value is 'false', it will just erase the first occurrence.     */    void eraseObject(T object, bool removeAll = false)    {        CCASSERT(object != nullptr, "The object should not be nullptr");                if (removeAll)        {            for (auto iter = _data.begin(); iter != _data.end();)            {                if ((*iter) == object)                {                    iter = _data.erase(iter);                    object->release();                }                else                {                    ++iter;                }            }        }        else        {            auto iter = std::find(_data.begin(), _data.end(), object);            if (iter != _data.end())            {                _data.erase(iter);                object->release();            }        }    }    /** @brief Removes from the vector with an iterator.      *  @param position Iterator pointing to a single element to be removed from the vector.     *  @return An iterator pointing to the new location of the element that followed the last element erased by the function call.     *          This is the container end if the operation erased the last element in the sequence.     */    iterator erase(iterator position)    {        CCASSERT(position >= _data.begin() && position < _data.end(), "Invalid position!");        (*position)->release();        return _data.erase(position);    }        /** @brief Removes from the vector with a range of elements (  [first, last)  ).     *  @param first The beginning of the range     *  @param last The end of the range, the 'last' will not used, it's only for indicating the end of range.     *  @return An iterator pointing to the new location of the element that followed the last element erased by the function call.     *          This is the container end if the operation erased the last element in the sequence.     */    iterator erase(iterator first, iterator last)    {        for (auto iter = first; iter != last; ++iter)        {            (*iter)->release();        }                return _data.erase(first, last);    }        /** @brief Removes from the vector with an index.     *  @param index The index of the element to be removed from the vector.     *  @return An iterator pointing to the new location of the element that followed the last element erased by the function call.     *          This is the container end if the operation erased the last element in the sequence.     */    iterator erase(ssize_t index)    {        CCASSERT(!_data.empty() && index >=0 && index < size(), "Invalid index!");        auto it = std::next( begin(), index );        (*it)->release();        return _data.erase(it);    }    /** @brief Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.     *  @note All the elements in the vector will be released (referece count will be decreased).     */    void clear()    {        for( auto it = std::begin(_data); it != std::end(_data); ++it ) {            (*it)->release();        }        _data.clear();    }    // Rearranging Content    /** Swap two elements */    void swap(T object1, T object2)    {        ssize_t idx1 = getIndex(object1);        ssize_t idx2 = getIndex(object2);        CCASSERT(idx1>=0 && idx2>=0, "invalid object index");        std::swap( _data[idx1], _data[idx2] );    }        /** Swap two elements with certain indexes */    void swap(ssize_t index1, ssize_t index2)    {        CCASSERT(index1 >=0 && index1 < size() && index2 >= 0 && index2 < size(), "Invalid indices");        std::swap( _data[index1], _data[index2] );    }    /** Replace object at index with another object. */    void replace(ssize_t index, T object)    {        CCASSERT(index >= 0 && index < size(), "Invalid index!");        CCASSERT(object != nullptr, "The object should not be nullptr");                _data[index]->release();        _data[index] = object;        object->retain();    }    /** reverses the vector */    void reverse()    {        std::reverse( std::begin(_data), std::end(_data) );    }        /** Shrinks the vector so the memory footprint corresponds with the number of items */    void shrinkToFit()    {        _data.shrink_to_fit();    }    protected:        /** Retains all the objects in the vector */    void addRefForAllObjects()    {        for(const auto &obj : _data) {            obj->retain();        }    }        std::vector<T> _data;};// end of data_structure group/// @}NS_CC_END#endif // __CCVECTOR_H__

我们可以发现,基本时对标准c++的vector进行了封装,在诸如与所添加对象相关的如insert,push_back,构造函数中加入了retain()方法,而在与删除对象相关的的popback,erase,析构函数等方法中加入release方法,进行计数的减1。从而即能够利用c++标准库的vector带来的使用便利和效率提升,更加符合c++开发者的习惯,也满足了对与内存管理的需要,减少了内存泄漏的可能性。


对与map,思路和vector总体类似,由于map采用的pair作为底层的结构,固为键值对的形式存在,其中包含了一些关于键值的操作。具体的使用如下所示,代码在ccmap.h中:

/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies  http://www.cocos2d-x.org  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/#ifndef __CCMAP_H__#define __CCMAP_H__#define USE_STD_UNORDERED_MAP 1#include "ccMacros.h"#include "CCRef.h"#include <vector>#if USE_STD_UNORDERED_MAP#include <unordered_map>#else#include <map>#endifNS_CC_BEGIN/** * @addtogroup data_structures * @{ */template <class K, class V>class CC_DLL Map{public:    // ------------------------------------------    // Iterators    // ------------------------------------------#if USE_STD_UNORDERED_MAP    typedef std::unordered_map<K, V> RefMap;#else    typedef std::map<K, V> RefMap;#endif        typedef typename RefMap::iterator iterator;    typedef typename RefMap::const_iterator const_iterator;        iterator begin() { return _data.begin(); }    const_iterator begin() const { return _data.begin(); }        iterator end() { return _data.end(); }    const_iterator end() const { return _data.end(); }        const_iterator cbegin() const { return _data.cbegin(); }    const_iterator cend() const { return _data.cend(); }        /** Default constructor */    Map<K, V>()    : _data()    {        static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");        CCLOGINFO("In the default constructor of Map!");    }        /** Contructor with capacity */    explicit Map<K, V>(ssize_t capacity)    : _data()    {        static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");        CCLOGINFO("In the constructor with capacity of Map!");        _data.reserve(capacity);    }        /** Copy constructor */    Map<K, V>(const Map<K, V>& other)    {        static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");        CCLOGINFO("In the copy constructor of Map!");        _data = other._data;        addRefForAllObjects();    }        /** Move constructor */    Map<K, V>(Map<K, V>&& other)    {        static_assert(std::is_convertible<V, Ref*>::value, "Invalid Type for cocos2d::Map<K, V>!");        CCLOGINFO("In the move constructor of Map!");        _data = std::move(other._data);    }        /** Destructor     *  It will release all objects in map.     */    ~Map<K, V>()    {        CCLOGINFO("In the destructor of Map!");        clear();    }        /** Sets capacity of the map */    void reserve(ssize_t capacity)    {#if USE_STD_UNORDERED_MAP        _data.reserve(capacity);#endif    }        /** Returns the number of buckets in the Map container. */    ssize_t bucketCount() const    {#if USE_STD_UNORDERED_MAP        return _data.bucket_count();#else        return 0;#endif    }        /** Returns the number of elements in bucket n. */    ssize_t bucketSize(ssize_t n) const    {#if USE_STD_UNORDERED_MAP        return _data.bucket_size(n);#else        return 0;#endif    }        /** Returns the bucket number where the element with key k is located. */    ssize_t bucket(const K& k) const    {#if USE_STD_UNORDERED_MAP        return _data.bucket(k);#else        return 0;#endif    }        /** The number of elements in the map. */    ssize_t size() const    {        return _data.size();    }        /** Returns a bool value indicating whether the map container is empty, i.e. whether its size is 0.     *  @note This function does not modify the content of the container in any way.     *        To clear the content of an array object, member function unordered_map::clear exists.     */    bool empty() const    {        return _data.empty();    }        /** Returns all keys in the map */    std::vector<K> keys() const    {        std::vector<K> keys;        if (!_data.empty())        {            keys.reserve(_data.size());                        for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)            {                keys.push_back(iter->first);            }        }        return keys;    }        /** Returns all keys that matches the object */    std::vector<K> keys(V object) const    {        std::vector<K> keys;                if (!_data.empty())        {            keys.reserve(_data.size() / 10);                        for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)            {                if (iter->second == object)                {                    keys.push_back(iter->first);                }            }        }                keys.shrink_to_fit();                return keys;    }        /** @brief Returns a reference to the mapped value of the element with key k in the map.     *  @note If key does not match the key of any element in the container, the function return nullptr.     *  @param key Key value of the element whose mapped value is accessed.     *       Member type K is the keys for the elements in the container. defined in Map<K, V> as an alias of its first template parameter (Key).     */    const V at(const K& key) const    {        auto iter = _data.find(key);        if (iter != _data.end())            return iter->second;        return nullptr;    }        V at(const K& key)    {        auto iter = _data.find(key);        if (iter != _data.end())            return iter->second;        return nullptr;    }        /** @brief Searches the container for an element with 'key' as key and returns an iterator to it if found,     *         otherwise it returns an iterator to Map<K, V>::end (the element past the end of the container).     *  @param key Key to be searched for.     *         Member type 'K' is the type of the keys for the elements in the container,     *         defined in Map<K, V> as an alias of its first template parameter (Key).     *     */    const_iterator find(const K& key) const    {        return _data.find(key);    }        iterator find(const K& key)    {        return _data.find(key);    }        /** @brief Inserts new elements in the map.     *  @note If the container has already contained the key, this function will erase the old pair(key, object)  and insert the new pair.     *  @param key The key to be inserted.     *  @param object The object to be inserted.     */    void insert(const K& key, V object)    {        CCASSERT(object != nullptr, "Object is nullptr!");        erase(key);        _data.insert(std::make_pair(key, object));        object->retain();    }        /** @brief Removes an element with an iterator from the Map<K, V> container.     *  @param position Iterator pointing to a single element to be removed from the Map<K, V>.     *         Member type const_iterator is a forward iterator type.     */    iterator erase(const_iterator position)    {        CCASSERT(position != _data.cend(), "Invalid iterator!");        position->second->release();        return _data.erase(position);    }        /** @brief Removes an element with an iterator from the Map<K, V> container.     *  @param k Key of the element to be erased.     *         Member type 'K' is the type of the keys for the elements in the container,     *         defined in Map<K, V> as an alias of its first template parameter (Key).     */    size_t erase(const K& k)    {        auto iter = _data.find(k);        if (iter != _data.end())        {            iter->second->release();            _data.erase(iter);            return 1;        }                return 0;    }        /** @brief Removes some elements with a vector which contains keys in the map.     *  @param keys Keys of elements to be erased.     */    void erase(const std::vector<K>& keys)    {        for(const auto &key : keys) {            this->erase(key);        }    }        /** All the elements in the Map<K,V> container are dropped:     *  their reference count will be decreased, and they are removed from the container,     *  leaving it with a size of 0.     */    void clear()    {        for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter)        {            iter->second->release();        }                _data.clear();    }        /** @brief Gets a random object in the map     *  @return Returns the random object if the map isn't empty, otherwise it returns nullptr.     */    V getRandomObject() const    {        if (!_data.empty())        {            ssize_t randIdx = rand() % _data.size();            const_iterator randIter = _data.begin();            std::advance(randIter , randIdx);            return randIter->second;        }        return nullptr;    }        // Don't uses operator since we could not decide whether it needs 'retain'/'release'.    //    V& operator[] ( const K& key )    //    {    //        CCLOG("copy: [] ref");    //        return _data[key];    //    }    //    //    V& operator[] ( K&& key )    //    {    //        CCLOG("move [] ref");    //        return _data[key];    //    }        //    const V& operator[] ( const K& key ) const    //    {    //        CCLOG("const copy []");    //        return _data.at(key);    //    }    //    //    const V& operator[] ( K&& key ) const    //    {    //        CCLOG("const move []");    //        return _data.at(key);    //    }        /** Copy assignment operator */    Map<K, V>& operator= ( const Map<K, V>& other )    {        if (this != &other) {            CCLOGINFO("In the copy assignment operator of Map!");            clear();            _data = other._data;            addRefForAllObjects();        }        return *this;    }        /** Move assignment operator */    Map<K, V>& operator= ( Map<K, V>&& other )    {        if (this != &other) {            CCLOGINFO("In the move assignment operator of Map!");            clear();            _data = std::move(other._data);        }        return *this;    }    protected:        /** Retains all the objects in the map */    void addRefForAllObjects()    {        for (auto iter = _data.begin(); iter != _data.end(); ++iter)        {            iter->second->retain();        }    }        RefMap _data;};// end of data_structure group/// @}NS_CC_END#endif /* __CCMAP_H__ */

最后比较有意思的时value,是cocos2d-x独有的设计,对基本数据类型进行包装,并在其中对vector也map也进行了相关的封装,其中主要包括了构造函数和复制操作符,在构造函数中对类型进行了相关的赋值,头文件在ccvalue.h文件中,并在对应的cpp文件中进行了实现。

/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies  http://www.cocos2d-x.org  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/#ifndef __cocos2d_libs__CCValue__#define __cocos2d_libs__CCValue__#include "CCPlatformMacros.h"#include "ccMacros.h"#include <string>#include <vector>#include <unordered_map>NS_CC_BEGINclass Value;typedef std::vector<Value> ValueVector;typedef std::unordered_map<std::string, Value> ValueMap;typedef std::unordered_map<int, Value> ValueMapIntKey;class Value{public:    static const Value Null;        Value();    explicit Value(unsigned char v);    explicit Value(int v);    explicit Value(float v);    explicit Value(double v);    explicit Value(bool v);    explicit Value(const char* v);    explicit Value(const std::string& v);        explicit Value(const ValueVector& v);    explicit Value(ValueVector&& v);        explicit Value(const ValueMap& v);explicit Value(ValueMap&& v);        explicit Value(const ValueMapIntKey& v);    explicit Value(ValueMapIntKey&& v);        Value(const Value& other);    Value(Value&& other);    ~Value();        // assignment operator    Value& operator= (const Value& other);    Value& operator= (Value&& other);        Value& operator= (unsigned char v);    Value& operator= (int v);    Value& operator= (float v);    Value& operator= (double v);    Value& operator= (bool v);    Value& operator= (const char* v);    Value& operator= (const std::string& v);        Value& operator= (const ValueVector& v);    Value& operator= (ValueVector&& v);        Value& operator= (const ValueMap& v);Value& operator= (ValueMap&& v);        Value& operator= (const ValueMapIntKey& v);    Value& operator= (ValueMapIntKey&& v);        unsigned char asByte() const;    int asInt() const;    float asFloat() const;    double asDouble() const;    bool asBool() const;    std::string asString() const;        ValueVector& asValueVector();    const ValueVector& asValueVector() const;        ValueMap& asValueMap();    const ValueMap& asValueMap() const;        ValueMapIntKey& asIntKeyMap();    const ValueMapIntKey& asIntKeyMap() const;    inline bool isNull() const { return _type == Type::NONE; }        enum class Type    {        NONE,        BYTE,        INTEGER,        FLOAT,        DOUBLE,        BOOLEAN,        STRING,        VECTOR,        MAP,        INT_KEY_MAP    };    inline Type getType() const { return _type; };        std::string getDescription();    private:    void clear();        union    {        unsigned char byteVal;        int intVal;        float floatVal;        double doubleVal;        bool boolVal;    }_baseData;        std::string _strData;    ValueVector* _vectorData;    ValueMap* _mapData;    ValueMapIntKey* _intKeyMapData;    Type _type;};NS_CC_END#endif /* defined(__cocos2d_libs__CCValue__) */

通过对类型的赋值和识别,能够正确的存储cocos2d-x开发中用到的基本数据类型和vector,map等容器的使用。具体的cpp代码如下所示:

/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies  http://www.cocos2d-x.org  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/#include "CCValue.h"#include <sstream>#include <iomanip>NS_CC_BEGINconst Value Value::Null;Value::Value(): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::NONE){    }Value::Value(unsigned char v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::BYTE){    _baseData.byteVal = v;}Value::Value(int v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::INTEGER){    _baseData.intVal = v;}Value::Value(float v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::FLOAT){    _baseData.floatVal = v;}Value::Value(double v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::DOUBLE){    _baseData.doubleVal = v;}Value::Value(bool v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::BOOLEAN){    _baseData.boolVal = v;}Value::Value(const char* v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::STRING){    _strData = v;}Value::Value(const std::string& v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::STRING){    _strData = v;}Value::Value(const ValueVector& v): _vectorData(new ValueVector()), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::VECTOR){    *_vectorData = v;}Value::Value(ValueVector&& v): _vectorData(new ValueVector()), _mapData(nullptr), _intKeyMapData(nullptr), _type(Type::VECTOR){    *_vectorData = std::move(v);}Value::Value(const ValueMap& v): _vectorData(nullptr), _mapData(new ValueMap()), _intKeyMapData(nullptr), _type(Type::MAP){    *_mapData = v;}Value::Value(ValueMap&& v): _vectorData(nullptr), _mapData(new ValueMap()), _intKeyMapData(nullptr), _type(Type::MAP){    *_mapData = std::move(v);}Value::Value(const ValueMapIntKey& v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(new ValueMapIntKey()), _type(Type::INT_KEY_MAP){    *_intKeyMapData = v;}Value::Value(ValueMapIntKey&& v): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(new ValueMapIntKey()), _type(Type::INT_KEY_MAP){    *_intKeyMapData = std::move(v);}Value::Value(const Value& other): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr){    *this = other;}Value::Value(Value&& other): _vectorData(nullptr), _mapData(nullptr), _intKeyMapData(nullptr){    *this = std::move(other);}Value::~Value(){    clear();}Value& Value::operator= (const Value& other){    if (this != &other) {        switch (other._type) {            case Type::BYTE:                _baseData.byteVal = other._baseData.byteVal;                break;            case Type::INTEGER:                _baseData.intVal = other._baseData.intVal;                break;            case Type::FLOAT:                _baseData.floatVal = other._baseData.floatVal;                break;            case Type::DOUBLE:                _baseData.doubleVal = other._baseData.doubleVal;                break;            case Type::BOOLEAN:                _baseData.boolVal = other._baseData.boolVal;                break;            case Type::STRING:                _strData = other._strData;                break;            case Type::VECTOR:                if (_vectorData == nullptr)                    _vectorData = new ValueVector();                *_vectorData = *other._vectorData;                break;            case Type::MAP:                if (_mapData == nullptr)                    _mapData = new ValueMap();                *_mapData = *other._mapData;                break;            case Type::INT_KEY_MAP:                if (_intKeyMapData == nullptr)                    _intKeyMapData = new ValueMapIntKey();                *_intKeyMapData = *other._intKeyMapData;                break;            default:                break;        }        _type = other._type;    }    return *this;}Value& Value::operator= (Value&& other){    if (this != &other) {        switch (other._type) {            case Type::BYTE:                _baseData.byteVal = other._baseData.byteVal;                break;            case Type::INTEGER:                _baseData.intVal = other._baseData.intVal;                break;            case Type::FLOAT:                _baseData.floatVal = other._baseData.floatVal;                break;            case Type::DOUBLE:                _baseData.doubleVal = other._baseData.doubleVal;                break;            case Type::BOOLEAN:                _baseData.boolVal = other._baseData.boolVal;                break;            case Type::STRING:                _strData = other._strData;                break;            case Type::VECTOR:                CC_SAFE_DELETE(_vectorData);                _vectorData = other._vectorData;                break;            case Type::MAP:                CC_SAFE_DELETE(_mapData);                _mapData = other._mapData;                break;            case Type::INT_KEY_MAP:                CC_SAFE_DELETE(_intKeyMapData);                _intKeyMapData = other._intKeyMapData;                break;            default:                break;        }        _type = other._type;                other._vectorData = nullptr;        other._mapData = nullptr;        other._intKeyMapData = nullptr;        other._type = Type::NONE;    }        return *this;}Value& Value::operator= (unsigned char v){    clear();    _type = Type::BYTE;    _baseData.byteVal = v;    return *this;}Value& Value::operator= (int v){    clear();    _type = Type::INTEGER;    _baseData.intVal = v;    return *this;}Value& Value::operator= (float v){    clear();    _type = Type::FLOAT;    _baseData.floatVal = v;    return *this;}Value& Value::operator= (double v){    clear();    _type = Type::DOUBLE;    _baseData.doubleVal = v;    return *this;}Value& Value::operator= (bool v){    clear();    _type = Type::BOOLEAN;    _baseData.boolVal = v;    return *this;}Value& Value::operator= (const char* v){    clear();    _type = Type::STRING;    _strData = v ? v : "";    return *this;}Value& Value::operator= (const std::string& v){    clear();    _type = Type::STRING;    _strData = v;    return *this;}Value& Value::operator= (const ValueVector& v){    clear();    _type = Type::VECTOR;    _vectorData = new ValueVector();    *_vectorData = v;    return *this;}Value& Value::operator= (ValueVector&& v){    clear();    _type = Type::VECTOR;    _vectorData = new ValueVector();    *_vectorData = std::move(v);    return *this;}Value& Value::operator= (const ValueMap& v){    clear();    _type = Type::MAP;    _mapData = new ValueMap();    *_mapData = v;    return *this;}Value& Value::operator= (ValueMap&& v){    clear();    _type = Type::MAP;    _mapData = new ValueMap();    *_mapData = std::move(v);    return *this;}Value& Value::operator= (const ValueMapIntKey& v){    clear();    _type = Type::INT_KEY_MAP;    _intKeyMapData = new ValueMapIntKey();    *_intKeyMapData = v;    return *this;}Value& Value::operator= (ValueMapIntKey&& v){    clear();    _type = Type::INT_KEY_MAP;    _intKeyMapData = new ValueMapIntKey();    *_intKeyMapData = std::move(v);    return *this;}///unsigned char Value::asByte() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");        if (_type == Type::BYTE)    {        return _baseData.byteVal;    }        if (_type == Type::INTEGER)    {        return static_cast<unsigned char>(_baseData.intVal);    }        if (_type == Type::STRING)    {        return static_cast<unsigned char>(atoi(_strData.c_str()));    }        if (_type == Type::FLOAT)    {        return static_cast<unsigned char>(_baseData.floatVal);    }        if (_type == Type::DOUBLE)    {        return static_cast<unsigned char>(_baseData.doubleVal);    }        if (_type == Type::BOOLEAN)    {        return _baseData.boolVal ? 1 : 0;    }        return 0;}int Value::asInt() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");    if (_type == Type::INTEGER)    {        return _baseData.intVal;    }        if (_type == Type::BYTE)    {        return _baseData.byteVal;    }        if (_type == Type::STRING)    {        return atoi(_strData.c_str());    }        if (_type == Type::FLOAT)    {        return static_cast<int>(_baseData.floatVal);    }        if (_type == Type::DOUBLE)    {        return static_cast<int>(_baseData.doubleVal);    }        if (_type == Type::BOOLEAN)    {        return _baseData.boolVal ? 1 : 0;    }        return 0;}float Value::asFloat() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");    if (_type == Type::FLOAT)    {        return _baseData.floatVal;    }        if (_type == Type::BYTE)    {        return static_cast<float>(_baseData.byteVal);    }        if (_type == Type::STRING)    {        return atof(_strData.c_str());    }        if (_type == Type::INTEGER)    {        return static_cast<float>(_baseData.intVal);    }        if (_type == Type::DOUBLE)    {        return static_cast<float>(_baseData.doubleVal);    }        if (_type == Type::BOOLEAN)    {        return _baseData.boolVal ? 1.0f : 0.0f;    }        return 0.0f;}double Value::asDouble() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");    if (_type == Type::DOUBLE)    {        return _baseData.doubleVal;    }        if (_type == Type::BYTE)    {        return static_cast<double>(_baseData.byteVal);    }        if (_type == Type::STRING)    {        return static_cast<double>(atof(_strData.c_str()));    }        if (_type == Type::INTEGER)    {        return static_cast<double>(_baseData.intVal);    }        if (_type == Type::FLOAT)    {        return static_cast<double>(_baseData.floatVal);    }        if (_type == Type::BOOLEAN)    {        return _baseData.boolVal ? 1.0 : 0.0;    }        return 0.0;}bool Value::asBool() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");    if (_type == Type::BOOLEAN)    {        return _baseData.boolVal;    }        if (_type == Type::BYTE)    {        return _baseData.byteVal == 0 ? false : true;    }        if (_type == Type::STRING)    {        return (_strData == "0" || _strData == "false") ? false : true;    }        if (_type == Type::INTEGER)    {        return _baseData.intVal == 0 ? false : true;    }        if (_type == Type::FLOAT)    {        return _baseData.floatVal == 0.0f ? false : true;    }        if (_type == Type::DOUBLE)    {        return _baseData.doubleVal == 0.0 ? false : true;    }        return true;}std::string Value::asString() const{    CCASSERT(_type != Type::VECTOR && _type != Type::MAP, "");        if (_type == Type::STRING)    {        return _strData;    }        std::stringstream ret;        switch (_type) {        case Type::BYTE:            ret << _baseData.byteVal;            break;        case Type::INTEGER:            ret << _baseData.intVal;            break;        case Type::FLOAT:            ret << std::fixed << std::setprecision( 7 )<< _baseData.floatVal;            break;        case Type::DOUBLE:            ret << std::fixed << std::setprecision( 16 ) << _baseData.doubleVal;            break;        case Type::BOOLEAN:            ret << (_baseData.boolVal ? "true" : "false");            break;        default:            break;    }    return ret.str();}ValueVector& Value::asValueVector(){if (nullptr == _vectorData)_vectorData = new ValueVector();return *_vectorData;}const ValueVector& Value::asValueVector() const{static const ValueVector EMPTY_VALUEVECTOR;if (nullptr == _vectorData)return EMPTY_VALUEVECTOR;return *_vectorData; }ValueMap& Value::asValueMap(){if (nullptr == _mapData)_mapData = new ValueMap();return *_mapData;}const ValueMap& Value::asValueMap() const{static const ValueMap EMPTY_VALUEMAP;if (nullptr == _mapData)return EMPTY_VALUEMAP;return *_mapData;}ValueMapIntKey& Value::asIntKeyMap(){if (nullptr == _intKeyMapData)_intKeyMapData = new ValueMapIntKey();return *_intKeyMapData;}const ValueMapIntKey& Value::asIntKeyMap() const{static const ValueMapIntKey EMPTY_VALUEMAP_INT_KEY;if (nullptr == _intKeyMapData)return EMPTY_VALUEMAP_INT_KEY;return *_intKeyMapData;}static std::string getTabs(int depth){    std::string tabWidth;        for (int i = 0; i < depth; ++i)    {        tabWidth += "\t";    }        return tabWidth;}static std::string visit(const Value& v, int depth);static std::string visitVector(const ValueVector& v, int depth){    std::stringstream ret;        if (depth > 0)        ret << "\n";        ret << getTabs(depth) << "[\n";        int i = 0;    for (const auto& child : v)    {        ret << getTabs(depth+1) << i << ": " << visit(child, depth + 1);        ++i;    }        ret << getTabs(depth) << "]\n";        return ret.str();}template <class T>static std::string visitMap(const T& v, int depth){    std::stringstream ret;        if (depth > 0)        ret << "\n";        ret << getTabs(depth) << "{\n";        for (auto iter = v.begin(); iter != v.end(); ++iter)    {        ret << getTabs(depth + 1) << iter->first << ": ";        ret << visit(iter->second, depth + 1);    }        ret << getTabs(depth) << "}\n";        return ret.str();}static std::string visit(const Value& v, int depth){    std::stringstream ret;    switch (v.getType())    {        case Value::Type::NONE:        case Value::Type::BYTE:        case Value::Type::INTEGER:        case Value::Type::FLOAT:        case Value::Type::DOUBLE:        case Value::Type::BOOLEAN:        case Value::Type::STRING:            ret << v.asString() << "\n";            break;        case Value::Type::VECTOR:            ret << visitVector(v.asValueVector(), depth);            break;        case Value::Type::MAP:            ret << visitMap(v.asValueMap(), depth);            break;        case Value::Type::INT_KEY_MAP:            ret << visitMap(v.asIntKeyMap(), depth);            break;        default:            CCASSERT(false, "Invalid type!");            break;    }        return ret.str();}std::string Value::getDescription(){    std::string ret("\n");    ret += visit(*this, 0);    return ret;}void Value::clear(){    _type = Type::NONE;    _baseData.doubleVal = 0.0;    _strData.clear();    CC_SAFE_DELETE(_vectorData);    CC_SAFE_DELETE(_mapData);    CC_SAFE_DELETE(_intKeyMapData);}NS_CC_END

通过在构造函数中对类型进行赋值,在赋值操作符对类型进行提取,并有相关的as方法进行类型判断。


总结就是cocos2d-x的这次对数据存储类型的改动很好的结合了c++的特性和习惯,并融合oc的内存管理体系,拜托了对oc的数据模式的依赖,更加符合c++的开发规范。

0 0