Skip to content

Latest commit

 

History

History
35 lines (28 loc) · 724 Bytes

16.1 When Generic Code Doesn't Quiet Cut It.md

File metadata and controls

35 lines (28 loc) · 724 Bytes

当“泛型代码”不能很好的解决问题时

考虑以下代码:

template<class T>
class Array{
private:
	T* data;
    
public:
    Array(Array<T> const&);
    Array<T>& operator=(Array<T> const&);
    
    void exchangeWith(Array<T>* b){
        T* tmp=data;
        data=b->data;
        b->data=tmp;
    }
    
    T& operator[](std::size_t n)const{
        return data[n];
    }
    ...
};

template<class T>
inline exchange(T* lhs,T* rhs){
    T tmp=*rhs;
    *lhs=*rhs;
    *rhs=tmp;
}

显然,exchange这个泛型代码问题很多,当T为复杂类型时,需要拷贝构造和赋值,代价大,简单的交换结构的内部指针就能省去不必要的拷贝(exchangeWith