关于C++标准程序库问答

王朝c/c++·作者佚名  2006-01-06
窄屏简体版  字體: |||超大  

为什么在这要一个原型的,一个泛型的构造函数,如果是泛型时可不可以替代copy构造函数

auto_ptr (auto_ptr& rhs) throw()

: ap(rhs.release()) {

}

template<class Y>

auto_ptr (auto_ptr<Y>& rhs) throw()

: ap(rhs.release()) {

}

如下列Code:

namespace std {

// auxiliary type to enable copies and assignments (now global)

template<class Y>

struct auto_ptr_ref {

Y* yp;

auto_ptr_ref (Y* rhs)

: yp(rhs) {

}

};

template<class T>

class auto_ptr {

private:

T* ap; // refers to the actual owned object (if any)

public:

typedef T element_type;

// constructor

explicit auto_ptr (T* ptr = 0) throw()

: ap(ptr) {

}

// copy constructors (with implicit conversion)

// - note: nonconstant parameter

auto_ptr (auto_ptr& rhs) throw()

: ap(rhs.release()) {

}

template<class Y>

auto_ptr (auto_ptr<Y>& rhs) throw()

: ap(rhs.release()) {

}

// assignments (with implicit conversion)

// - note: nonconstant parameter

auto_ptr& operator= (auto_ptr& rhs) throw() {

reset(rhs.release());

return *this;

}

template<class Y>

auto_ptr& operator= (auto_ptr<Y>& rhs) throw() {

reset(rhs.release());

return *this;

}

// destructor

~auto_ptr() throw() {

delete ap;

}

// value access

T* get() const throw() {

return ap;

}

T& operator*() const throw() {

return *ap;

}

T* operator->() const throw() {

return ap;

}

// release ownership

T* release() throw() {

T* tmp(ap);

ap = 0;

return tmp;

}

// reset value

void reset (T* ptr=0) throw() {

if (ap != ptr) {

delete ap;

ap = ptr;

}

}

/* special conversions with auxiliary type to enable copies and assignments

*/

auto_ptr(auto_ptr_ref<T> rhs) throw()

: ap(rhs.yp) {

}

auto_ptr& operator= (auto_ptr_ref<T> rhs) throw() { // new

reset(rhs.yp);

return *this;

}

template<class Y>

operator auto_ptr_ref<Y>() throw() {

return auto_ptr_ref<Y>(release());

}

template<class Y>

operator auto_ptr<Y>() throw() {

return auto_ptr<Y>(release());

}

};

}

泛型的ctor是在类型转换的时候调用,可以替代原型的ctor,举个例子:

#include <iostream>

using namespace std;

class one {};

class two : public one {};

template <class T>

class a_ptr

{

private:

T* ap;

public:

a_ptr(T* ptr = 0) : ap(ptr) {}

a_ptr(a_ptr& rhs) : ap(rhs.release()) {}

template<class U>

a_ptr (a_ptr<U>& rhs) : ap(rhs.release()) {}

T* release()

{

T* tmp(ap);

ap = 0;

return tmp;

}

};

int main()

{

a_ptr<int> p1(new int);

a_ptr<int> p2(p1);

a_ptr<two> p3(new two);

a_ptr<one> p4(p3);

cin.get();

return 0;

}

如果只注释掉

a_ptr(a_ptr& rhs) : ap(rhs.release()) {}

代码还是可以编译

如果只注释掉

template<class U>

a_ptr (a_ptr<U>& rhs) : ap(rhs.release()) {}

a_ptr<one> p4(p3);

不能编译

如果两个都注释掉

…… 

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航