test_copy_move.cpp 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
/*
    tests/test_copy_move_policies.cpp -- 'copy' and 'move' return value policies
                                         and related tests

    Copyright (c) 2016 Ben North <ben@redfrontdoor.org>

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

#include <pybind11/stl.h>

13
14
15
#include "constructor_stats.h"
#include "pybind11_tests.h"

16
17
template <typename derived>
struct empty {
18
    static const derived &get_one() { return instance_; }
19
20
21
22
    static derived instance_;
};

struct lacking_copy_ctor : public empty<lacking_copy_ctor> {
23
    lacking_copy_ctor() = default;
24
    lacking_copy_ctor(const lacking_copy_ctor &other) = delete;
25
26
};

27
28
template <>
lacking_copy_ctor empty<lacking_copy_ctor>::instance_ = {};
29
30

struct lacking_move_ctor : public empty<lacking_move_ctor> {
31
    lacking_move_ctor() = default;
32
33
    lacking_move_ctor(const lacking_move_ctor &other) = delete;
    lacking_move_ctor(lacking_move_ctor &&other) = delete;
34
35
};

36
37
template <>
lacking_move_ctor empty<lacking_move_ctor>::instance_ = {};
38
39
40
41
42

/* Custom type caster move/copy test classes */
class MoveOnlyInt {
public:
    MoveOnlyInt() { print_default_created(this); }
43
    explicit MoveOnlyInt(int v) : value{v} { print_created(this, value); }
44
45
46
47
48
49
50
51
52
    MoveOnlyInt(MoveOnlyInt &&m) noexcept {
        print_move_created(this, m.value);
        std::swap(value, m.value);
    }
    MoveOnlyInt &operator=(MoveOnlyInt &&m) noexcept {
        print_move_assigned(this, m.value);
        std::swap(value, m.value);
        return *this;
    }
53
54
55
56
57
58
59
60
61
    MoveOnlyInt(const MoveOnlyInt &) = delete;
    MoveOnlyInt &operator=(const MoveOnlyInt &) = delete;
    ~MoveOnlyInt() { print_destroyed(this); }

    int value;
};
class MoveOrCopyInt {
public:
    MoveOrCopyInt() { print_default_created(this); }
62
    explicit MoveOrCopyInt(int v) : value{v} { print_created(this, value); }
63
64
65
66
67
68
69
70
71
    MoveOrCopyInt(MoveOrCopyInt &&m) noexcept {
        print_move_created(this, m.value);
        std::swap(value, m.value);
    }
    MoveOrCopyInt &operator=(MoveOrCopyInt &&m) noexcept {
        print_move_assigned(this, m.value);
        std::swap(value, m.value);
        return *this;
    }
72
73
74
75
76
    MoveOrCopyInt(const MoveOrCopyInt &c) {
        print_copy_created(this, c.value);
        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
        value = c.value;
    }
77
78
79
80
81
    MoveOrCopyInt &operator=(const MoveOrCopyInt &c) {
        print_copy_assigned(this, c.value);
        value = c.value;
        return *this;
    }
82
83
84
85
86
87
88
    ~MoveOrCopyInt() { print_destroyed(this); }

    int value;
};
class CopyOnlyInt {
public:
    CopyOnlyInt() { print_default_created(this); }
89
    explicit CopyOnlyInt(int v) : value{v} { print_created(this, value); }
90
91
92
93
94
    CopyOnlyInt(const CopyOnlyInt &c) {
        print_copy_created(this, c.value);
        // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
        value = c.value;
    }
95
96
97
98
99
    CopyOnlyInt &operator=(const CopyOnlyInt &c) {
        print_copy_assigned(this, c.value);
        value = c.value;
        return *this;
    }
100
101
102
103
    ~CopyOnlyInt() { print_destroyed(this); }

    int value;
};
104
105
PYBIND11_NAMESPACE_BEGIN(pybind11)
PYBIND11_NAMESPACE_BEGIN(detail)
106
107
template <>
struct type_caster<MoveOnlyInt> {
108
    PYBIND11_TYPE_CASTER(MoveOnlyInt, const_name("MoveOnlyInt"));
109
110
111
112
113
114
115
    bool load(handle src, bool) {
        value = MoveOnlyInt(src.cast<int>());
        return true;
    }
    static handle cast(const MoveOnlyInt &m, return_value_policy r, handle p) {
        return pybind11::cast(m.value, r, p);
    }
116
117
};

118
119
template <>
struct type_caster<MoveOrCopyInt> {
120
    PYBIND11_TYPE_CASTER(MoveOrCopyInt, const_name("MoveOrCopyInt"));
121
122
123
124
125
126
127
    bool load(handle src, bool) {
        value = MoveOrCopyInt(src.cast<int>());
        return true;
    }
    static handle cast(const MoveOrCopyInt &m, return_value_policy r, handle p) {
        return pybind11::cast(m.value, r, p);
    }
128
129
};

130
131
template <>
struct type_caster<CopyOnlyInt> {
132
133
protected:
    CopyOnlyInt value;
134

135
public:
136
    static constexpr auto name = const_name("CopyOnlyInt");
137
138
139
140
141
142
143
    bool load(handle src, bool) {
        value = CopyOnlyInt(src.cast<int>());
        return true;
    }
    static handle cast(const CopyOnlyInt &m, return_value_policy r, handle p) {
        return pybind11::cast(m.value, r, p);
    }
144
    static handle cast(const CopyOnlyInt *src, return_value_policy policy, handle parent) {
145
146
147
        if (!src) {
            return none().release();
        }
148
149
        return cast(*src, policy, parent);
    }
150
151
    explicit operator CopyOnlyInt *() { return &value; }
    explicit operator CopyOnlyInt &() { return value; }
152
153
    template <typename T>
    using cast_op_type = pybind11::detail::cast_op_type<T>;
154
};
155
156
PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(pybind11)
157

158
159
TEST_SUBMODULE(copy_move_policies, m) {
    // test_lacking_copy_ctor
160
    py::class_<lacking_copy_ctor>(m, "lacking_copy_ctor")
161
        .def_static("get_one", &lacking_copy_ctor::get_one, py::return_value_policy::copy);
162
    // test_lacking_move_ctor
163
    py::class_<lacking_move_ctor>(m, "lacking_move_ctor")
164
        .def_static("get_one", &lacking_move_ctor::get_one, py::return_value_policy::move);
165

166
    // test_move_and_copy_casts
167
    // NOLINTNEXTLINE(performance-unnecessary-value-param)
168
    m.def("move_and_copy_casts", [](const py::object &o) {
169
170
        int r = 0;
        r += py::cast<MoveOrCopyInt>(o).value; /* moves */
171
172
173
174
175
        r += py::cast<MoveOnlyInt>(o).value;   /* moves */
        r += py::cast<CopyOnlyInt>(o).value;   /* copies */
        auto m1(py::cast<MoveOrCopyInt>(o));   /* moves */
        auto m2(py::cast<MoveOnlyInt>(o));     /* moves */
        auto m3(py::cast<CopyOnlyInt>(o));     /* copies */
176
177
178
179
        r += m1.value + m2.value + m3.value;

        return r;
    });
180
181
182

    // test_move_and_copy_loads
    m.def("move_only", [](MoveOnlyInt m) { return m.value; });
183
    // Changing this breaks the existing test: needs careful review.
184
    // NOLINTNEXTLINE(performance-unnecessary-value-param)
185
    m.def("move_or_copy", [](MoveOrCopyInt m) { return m.value; });
186
    // Changing this breaks the existing test: needs careful review.
187
    // NOLINTNEXTLINE(performance-unnecessary-value-param)
188
    m.def("copy_only", [](CopyOnlyInt m) { return m.value; });
189
190
    m.def("move_pair",
          [](std::pair<MoveOnlyInt, MoveOrCopyInt> p) { return p.first.value + p.second.value; });
191
192
193
194
195
196
    m.def("move_tuple", [](std::tuple<MoveOnlyInt, MoveOrCopyInt, MoveOnlyInt> t) {
        return std::get<0>(t).value + std::get<1>(t).value + std::get<2>(t).value;
    });
    m.def("copy_tuple", [](std::tuple<CopyOnlyInt, CopyOnlyInt> t) {
        return std::get<0>(t).value + std::get<1>(t).value;
    });
197
198
199
200
201
202
203
204
    m.def("move_copy_nested",
          [](std::pair<MoveOnlyInt,
                       std::pair<std::tuple<MoveOrCopyInt, CopyOnlyInt, std::tuple<MoveOnlyInt>>,
                                 MoveOrCopyInt>> x) {
              return x.first.value + std::get<0>(x.second.first).value
                     + std::get<1>(x.second.first).value
                     + std::get<0>(std::get<2>(x.second.first)).value + x.second.second.value;
          });
205
206
207
208
    m.def("move_and_copy_cstats", []() {
        ConstructorStats::gc();
        // Reset counts to 0 so that previous tests don't affect later ones:
        auto &mc = ConstructorStats::get<MoveOrCopyInt>();
209
210
        mc.move_assignments = mc.move_constructions = mc.copy_assignments = mc.copy_constructions
            = 0;
211
        auto &mo = ConstructorStats::get<MoveOnlyInt>();
212
213
        mo.move_assignments = mo.move_constructions = mo.copy_assignments = mo.copy_constructions
            = 0;
214
        auto &co = ConstructorStats::get<CopyOnlyInt>();
215
216
        co.move_assignments = co.move_constructions = co.copy_assignments = co.copy_constructions
            = 0;
217
218
219
220
221
222
223
        py::dict d;
        d["MoveOrCopyInt"] = py::cast(mc, py::return_value_policy::reference);
        d["MoveOnlyInt"] = py::cast(mo, py::return_value_policy::reference);
        d["CopyOnlyInt"] = py::cast(co, py::return_value_policy::reference);
        return d;
    });
#ifdef PYBIND11_HAS_OPTIONAL
224
    // test_move_and_copy_load_optional
225
    m.attr("has_optional") = true;
226
227
228
229
230
231
232
    m.def("move_optional", [](std::optional<MoveOnlyInt> o) { return o->value; });
    m.def("move_or_copy_optional", [](std::optional<MoveOrCopyInt> o) { return o->value; });
    m.def("copy_optional", [](std::optional<CopyOnlyInt> o) { return o->value; });
    m.def("move_optional_tuple",
          [](std::optional<std::tuple<MoveOrCopyInt, MoveOnlyInt, CopyOnlyInt>> x) {
              return std::get<0>(*x).value + std::get<1>(*x).value + std::get<2>(*x).value;
          });
233
234
235
236
#else
    m.attr("has_optional") = false;
#endif

237
238
239
240
    // #70 compilation issue if operator new is not public - simple body added
    // but not needed on most compilers; MSVC and nvcc don't like a local
    // struct not having a method defined when declared, since it can not be
    // added later.
241
242
    struct PrivateOpNew {
        int value = 1;
243

244
    private:
245
246
        void *operator new(size_t bytes) {
            void *ptr = std::malloc(bytes);
247
            if (ptr) {
248
                return ptr;
249
            }
250
            throw std::bad_alloc{};
251
        }
252
    };
253
254
    py::class_<PrivateOpNew>(m, "PrivateOpNew").def_readonly("value", &PrivateOpNew::value);
    m.def("private_op_new_value", []() { return PrivateOpNew(); });
255
256
257
258
259
260
261
    m.def(
        "private_op_new_reference",
        []() -> const PrivateOpNew & {
            static PrivateOpNew x{};
            return x;
        },
        py::return_value_policy::reference);
262

263
    // test_move_fallback
264
265
266
    // #389: rvp::move should fall-through to copy on non-movable objects
    struct MoveIssue1 {
        int v;
267
        explicit MoveIssue1(int v) : v{v} {}
268
269
270
        MoveIssue1(const MoveIssue1 &c) = default;
        MoveIssue1(MoveIssue1 &&) = delete;
    };
271
272
273
    py::class_<MoveIssue1>(m, "MoveIssue1")
        .def(py::init<int>())
        .def_readwrite("value", &MoveIssue1::v);
274
275
276

    struct MoveIssue2 {
        int v;
277
        explicit MoveIssue2(int v) : v{v} {}
278
279
        MoveIssue2(MoveIssue2 &&) = default;
    };
280
281
282
    py::class_<MoveIssue2>(m, "MoveIssue2")
        .def(py::init<int>())
        .def_readwrite("value", &MoveIssue2::v);
283

284
285
286
287
288
289
290
291
    // #2742: Don't expect ownership of raw pointer to `new`ed object to be transferred with
    // `py::return_value_policy::move`
    m.def(
        "get_moveissue1",
        [](int i) { return std::unique_ptr<MoveIssue1>(new MoveIssue1(i)); },
        py::return_value_policy::move);
    m.def(
        "get_moveissue2", [](int i) { return MoveIssue2(i); }, py::return_value_policy::move);
292
293
294

    // Make sure that cast from pytype rvalue to other pytype works
    m.def("get_pytype_rvalue_castissue", [](double i) { return py::float_(i).cast<py::int_>(); });
295
}