auto_ptr.pass.cpp revision b64f8b07c104c6cc986570ac8ee0ed16a9f23976
1//===----------------------------------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// <memory>
11
12// template<class Y> explicit shared_ptr(auto_ptr<Y>&& r);
13
14#include <memory>
15#include <new>
16#include <cstdlib>
17#include <cassert>
18
19bool throw_next = false;
20
21void* operator new(std::size_t s) throw(std::bad_alloc)
22{
23    if (throw_next)
24        throw std::bad_alloc();
25    return std::malloc(s);
26}
27
28void  operator delete(void* p) throw()
29{
30    std::free(p);
31}
32
33struct B
34{
35    static int count;
36
37    B() {++count;}
38    B(const B&) {++count;}
39    virtual ~B() {--count;}
40};
41
42int B::count = 0;
43
44struct A
45    : public B
46{
47    static int count;
48
49    A() {++count;}
50    A(const A&) {++count;}
51    ~A() {--count;}
52};
53
54int A::count = 0;
55
56int main()
57{
58    {
59    std::auto_ptr<A> ptr(new A);
60    A* raw_ptr = ptr.get();
61#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
62    std::shared_ptr<B> p(std::move(ptr));
63#else
64    std::shared_ptr<B> p(ptr);
65#endif
66    assert(A::count == 1);
67    assert(B::count == 1);
68    assert(p.use_count() == 1);
69    assert(p.get() == raw_ptr);
70    assert(ptr.get() == 0);
71    }
72    assert(A::count == 0);
73    {
74    std::auto_ptr<A> ptr(new A);
75    A* raw_ptr = ptr.get();
76    throw_next = true;
77    try
78    {
79#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
80        std::shared_ptr<B> p(std::move(ptr));
81#else
82        std::shared_ptr<B> p(ptr);
83#endif
84        assert(false);
85    }
86    catch (...)
87    {
88        assert(A::count == 1);
89        assert(B::count == 1);
90        assert(ptr.get() == raw_ptr);
91    }
92    }
93    assert(A::count == 0);
94}
95