简体   繁体   中英

Deprecated implicitely-declared copy constructor

I am trying to wrap my head around a weird characteristic of implicitely-declared copy constructors. Take the following example. Once the user implements a custom destructor, the copy-constructor isn't trivial anymore, but is still generated.

#include <type_traits>
#include <cstdio>

struct test {
    test() = default;
    ~test() {
    }
    test(const test&) = default;
    int i{42};
};
static_assert(std::is_copy_constructible_v<test>, "werks"); // OK
static_assert(std::is_trivially_copy_constructible_v<test>, "sad"); // FAILS

int main() {
    test t;
    test t2(t);
    printf("%d\n", t2.i);
    return 0;
}

Online version : https://godbolt.org/z/t-8_W3

My understanding of trivial constructors is they are generated by the compiler. However, cppreference states :

The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor or user-defined copy assignment operator.

So, it seems there is one more state an implicitly-declared constructor can be in, which is "deprecated". It is not "trivial" and not user implemented, but still generated by your compiler... Is that correct? Does someone know a type trait or workaround to verify if a constructor is "deprecated"?

is_trivially_copy_constructible<T> also requires that T be trivially destructible. What this trait checks is if the hypothetical variable definition:

T t(declval<T const&>());

would invoke no non-trivial operations. But test is not trivially destructible, and that destruction is implicit in that construction.

If you change ~test() { } to ~test() = default , the assertion will no longer trigger.


The note about deprecation of implicitly defined constructor is irrelevant, as you have an explicitly defaulted copy constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM