大家看看这个类,谁有VC6.0以上的什么的,帮忙看看运行有问题吗
c++吧
全部回复
仅看楼主
level 11
whatofor 楼主
帮忙看看这个auto_ptr 是否正确。
display是我用来看运行状态的。
fun和主函数是我写 的。
总感觉 这个auto_ptr设计的有问题,但是现在没有 vc。
只有 C::B ,它这个debug貌似不给力。
2011年08月10日 08点08分 1
level 11
whatofor 楼主
#include<iostream>
#include<cstdlib>
using namespace std;
#define __STL_NOTHROW
template <class X> class auto_ptr {
private:
  X* ptr;
  mutable bool owns;
public:
void display()
{
    std::cout<<"address:"<<(void *)ptr<<"\towns:"<<owns<<"\tvalue:";
    if(ptr)
        std::cout<<*ptr;
    else
        std::cout<<"none value";
    //std::cout<<"\tis delete: "<<del;
    std::cout<<"\n";
}
  typedef X element_type;
  explicit auto_ptr(X* p = 0) __STL_NOTHROW : ptr(p), owns(p) {}
  auto_ptr(const auto_ptr& a) __STL_NOTHROW : ptr(a.ptr), owns(a.owns) {
    a.owns = 0;
  }
  template <class T> auto_ptr(const auto_ptr<T>& a) __STL_NOTHROW
    : ptr(a.ptr), owns(a.owns) {
      a.owns = 0;
  }
  auto_ptr& operator=(const auto_ptr& a) __STL_NOTHROW {
    if (&a != this) {
      if (owns)
      {
         delete ptr;
      }
      owns = a.owns;
      ptr = a.ptr;
      a.owns = 0;
    }
  }
  template <class T> auto_ptr& operator=(const auto_ptr<T>& a) __STL_NOTHROW {
    if (&a != this) {
      if (owns)
      {
          delete ptr;
      }
      owns = a.owns;
      ptr = a.ptr;
      a.owns = 0;
    }
  }
  ~auto_ptr() {
    if (owns)
    {
        delete ptr;
    }
  }
  X& operator*() const __STL_NOTHROW { return *ptr; }
  X* operator->() const __STL_NOTHROW { return ptr; }
  X* get() const __STL_NOTHROW { return ptr; }
  X* release() const __STL_NOTHROW { owns = false; return ptr;}
};
template<class T>
void fun(auto_ptr<T> &p)
{
    p.display();
    auto_ptr<T> q(p);
    q.display();
}
int main()
{
    auto_ptr<int> p(new int(5));
    p.display();
    fun<int>(p);
    p.display();
    *p=6;
    p.display();
    return 0;
}
2011年08月10日 08点08分 2
level 11
whatofor 楼主
auto_ptr到底是用来做什么的?
看了下C::B下 auto_ptr的实现,这个更加绝,
允许且只允许 一个auto_ptr 指向 某一个对象。
也就是说
auto_ptr p1,p2=new int(1);
p1=p2;
*p2=2;//这个都是错误的了
2011年08月10日 09点08分 3
level 12
auto_ptr只能实现堆指针所有权的传递(而非共享),p1=p2前p1为nullptr,p2拥有new int(1)的所有权;p1=p2时p2把new int(1)的所有权交给p1,p2被重新赋值nullptr。
实现所有权共享使用shared_ptr
2011年08月10日 09点08分 4
level 11
whatofor 楼主
那auto_ptr主要是在什么情况下使用?
感觉很鸡肋
2011年08月10日 09点08分 5
level 12
在你懒得写delete时[拍砖]
2011年08月10日 09点08分 6
level 11
whatofor 楼主
放弃auto_ptr.
2011年08月10日 09点08分 7
level 12
delete真的不好写的
比如你想往容器里放堆指针的时候,元素的删除是容器自动完成,但容器却不会帮你delete掉你new出的指针
这时候使用智能指针不是很好么?
当然我是指auto_ptr的替代者unique_ptr
2011年08月10日 09点08分 9
level 15
不止是偷懒,主要是考虑异常。抛出异常的时候如果对象数量多手写delete会写到吐还容易漏。
不过没法放到容器是鸡肋。这个在C++03没办法简单地解决(需要使用复杂的模板技术实现右值引用类型)。C++0x下用unique_ptr代替。
2011年08月10日 22点08分 10
level 11
whatofor 楼主
share_ptr<T>&& rhs...
2011年08月11日 00点08分 11
1