1

下面是我的代码:

template<class t>
class smart_ptr{
    t *ptr;
public: 
    smart_ptr(t *p):ptr(p){cout<<"smart pointer copy constructor is called"<<endl;}    
    smart_ptr(const smart_ptr &sm){cout<<"copy constructor is called"
                                   <<endl;ptr=sm->ptr;}   
    ~smart_ptr(){cout<<"smart pointer destructor is called"<<endl;delete(ptr);}
    t& operator *(){cout<<"returning the * of pointer"<<endl;return(*ptr);}
    t* operator ->(){cout<<"returning the -> of pointer"<<endl;return(ptr);}
    t& operator=(const t &lhs){ptr=lhs->ptr;cout<<"assignement operator called"
                                 <<endl;return *this;}

    };
    class xxx{
            int x;
    public:
            xxx(int y=0):x(y){cout<<"xxx constructor called"<<endl;}
            ~xxx(){cout<<"xxx destructor is called"<<endl;}
            void show(){cout<<"the value of x="<<x<<endl;}
    };
int main(int argc, char *argv[])
{
    xxx *x1=new xxx(50);
    smart_ptr<xxx> p2(new xxx(60));
    smart_ptr<xxx> p1(x1);
    p1->show();
    smart_ptr<xxx> p3(p2);     //calling copy construcotr is giving error
    p3=p1;                     //calling assignment operator is giving error
    p2->smart_ptr<class xxx>::~smart_ptr<class xxx>(); //calling smart pointer 
                                                        destructor gives error
    return 0;
}

由于错误的复制构造函数、赋值运算符和析构函数代码,我在编译此文件时遇到编译错误。

错误是:

  smart_pointer_impl.cpp: In function ‘int main(int, char**)’:

  smart_pointer_impl.cpp:33: error: ‘smart_ptr<xxx>’ is not a base of ‘xxx’

  smart_pointer_impl.cpp: In copy constructor ‘smart_ptr<t>::smart_ptr(const 
  smart_ptr<t>&) [with t = xxx]’:

   smart_pointer_impl.cpp:28:   instantiated from here

   smart_pointer_impl.cpp:8: error: passing ‘const smart_ptr<xxx>’ as ‘this’ argument  
   of ‘t* 

   smart_ptr<t>::operator->() [with t = xxx]’ discards qualifiers

   smart_pointer_impl.cpp:8: error: ‘class xxx’ has no member named ‘ptr’

请找出我在上述功能中的错误之处。欢迎任何帮助。

4

2 回答 2

3

一个明显的错误是您的赋值运算符应该获取并返回对 的引用smart_ptr,而不是t

  smart_ptr& operator = (const smart_ptr& lhs)
//^^^^^^^^^                    ^^^^^^^^^

接下来,您的复制构造函数sm->ptr在它应该调用时调用sm.ptr,因为->已经重载以返回 a t

smart_ptr(const smart_ptr& sm) : ptr(sm.ptr) { .... }
于 2013-11-07T15:40:35.910 回答
2

通过以下更改可以修复编译错误:

    // copy ctor
    smart_ptr(const smart_ptr &sm)
      : ptr(sm.ptr)
    {
       cout<<"copy constructor is called" << endl;
    }

    // destructor's invocation
    p2.~smart_ptr();

但是,复制构造函数中存在逻辑错误,因为底层对象将被删除两次(或多次)。

于 2013-11-07T15:33:49.610 回答