lmi
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [lmi] Detecting whether move semantics actually take place


From: Vadim Zeitlin
Subject: Re: [lmi] Detecting whether move semantics actually take place
Date: Sun, 31 Jul 2022 14:41:51 +0200

 Sorry, I'd like to slightly amend what I wrote last night:

On Sun, 31 Jul 2022 03:14:09 +0200 I wrote:

Me> On Sun, 31 Jul 2022 00:41:37 +0000 Greg Chicares <gchicares@sbcglobal.net> 
wrote:
Me> 
Me> GC> In the modified example below, struct 'non_movable' is constructible and
Me> GC> assignable from 'non_movable&&' by using copy semantics, but not, AIUI,
Me> GC> by using move semantics.
Me> 
Me>  It does use move semantics.

 It still does...

Me>  I can prove this experimentally:

... but I think the demonstration can be improved. Instead of manually
defining copy and move ctors, which could be different from what the
compiler does by default, let's rely on the default-generated ctors:

---------------------------------- >8 --------------------------------------
% cat non_movable.cpp
#include <stdio.h>
#include <utility>

struct move_detector {
    explicit move_detector(int n) : n_{n} {}
    move_detector(move_detector const& x) : n_{x.n_} { printf("[%d] moved\n", 
n_); }
    move_detector(move_detector&& x) : n_{x.n_} { printf("[%d] moved\n", n_); }

    int n_;
};

struct base {
    ~base() = default;
};

struct non_movable : base {
    non_movable() = default;
    non_movable(non_movable const&) = default;
    non_movable(non_movable&&) = default;

    move_detector value{17};
};

int main() {
    non_movable x;
    return non_movable{std::move(x)}.value.n_;
}
% g++ -std=c++20 -Wall non_movable.cpp && ./a.out || echo $?
[17] moved
17
---------------------------------- >8 --------------------------------------

So the default-generated move ctor does move, rather than copy, the class
members, which is exactly what you'd expect.

 Also, adding move (and default, to avoid unrelated errors) ctors to "base"
prevents the default-generated move ctor from compiling (because it calls
the base class move ctor) and so makes the derived class non-movable:
again, as you'd expect it to do.

 So AFAICS everything works fine here and clang -Wdefaulted-function-deleted
is given when you'd expect it to be, i.e. when the defaulted function is
actually deleted.
 
 Regards,
VZ

Attachment: pgpLwDICLyWt5.pgp
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]