Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
move on copy
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#include <iostream> #include <memory> #include <utility> #include <type_traits> #include <functional> namespace detail { enum selection_enabler { enabled }; } #define ENABLE_IF(...) std::enable_if_t<(__VA_ARGS__), ::detail::selection_enabler> = ::detail::enabled // This allows forwarding an object using the copy constructor template <typename T> struct move_with_copy_ctor { // forwarding constructor template <typename T2 // Disable constructor for it's own type, since it would // conflict with the copy constructor. , ENABLE_IF( !std::is_same<std::remove_reference_t<T2>, move_with_copy_ctor>::value ) > move_with_copy_ctor(T2&& object) : wrapped_object(std::forward<T2>(object)) { } // move object to wrapped_object move_with_copy_ctor(T&& object) : wrapped_object(std::move(object)) { } // Copy constructor being used as move constructor. move_with_copy_ctor(move_with_copy_ctor const& object) { std::swap(wrapped_object, const_cast<move_with_copy_ctor&>(object).wrapped_object); } // access to wrapped object T& operator()() { return wrapped_object; } private: T wrapped_object; }; template <typename T> move_with_copy_ctor<T> make_movable(T&& object) { return{ std::forward<T>(object) }; } auto fn1() { std::unique_ptr<int, std::function<void(int*)>> x(new int(1) , [](int * x) { std::cout << "Destroying " << x << std::endl; delete x; }); return [y = make_movable(std::move(x))]() mutable { std::cout << "value: " << *y() << std::endl; return; }; } int main() { { auto x = fn1(); x(); std::cout << "object still not deleted\n"; x(); } std::cout << "object was deleted\n"; }
cl.exe
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 1,88 sec, absolute running time: 0,32 sec, absolute service time: 2,22 sec
edit mode
|
history
value: 1 object still not deleted value: 1 Destroying 0000009A06FC2120 object was deleted