首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代码中的智能指针实现错误

代码中的智能指针实现错误
EN

Stack Overflow用户
提问于 2013-11-07 23:21:42
回答 2查看 121关注 0票数 1

下面是我的代码:

代码语言:javascript
复制
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;
}

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

错误是:

代码语言:javascript
复制
  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’

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

EN

回答 2

Stack Overflow用户

发布于 2013-11-07 23:40:36

一个明显的错误是赋值操作符应该接受并返回对smart_ptr而不是t的引用

代码语言:javascript
复制
  smart_ptr& operator = (const smart_ptr& lhs)
//^^^^^^^^^                    ^^^^^^^^^

接下来,复制构造函数在应该调用sm.ptr的时候调用sm->ptr,因为->已经被重载,无论如何都会返回一个t

代码语言:javascript
复制
smart_ptr(const smart_ptr& sm) : ptr(sm.ptr) { .... }
票数 3
EN

Stack Overflow用户

发布于 2013-11-07 23:33:50

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

代码语言:javascript
复制
    // copy ctor
    smart_ptr(const smart_ptr &sm)
      : ptr(sm.ptr)
    {
       cout<<"copy constructor is called" << endl;
    }

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

然而,复制构造函数中有一个逻辑错误,因为底层对象将被删除两次(或多次)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19839697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档