mardi 12 septembre 2023

is there an error in “The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor”

I read this sentence in cppreference.It says The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor. Maybe there is an error.

I test in a code:

First I define destructor, copy/move constructor and copy/move assignment operator.

#include <iostream>
struct B {
    B() { std::cout << "B()" << std::endl; }
    ~B() { std::cout << "~B()" << std::endl; }

    B(const B&) { std::cout << "B(const B&)" << std::endl; }
    B& operator=(const B&) { std::cout << "B& operator=(const B&)" << std::endl; return *this; }

    B(B&&) { std::cout << "B(B&&)" << std::endl; }
    B& operator=(B&&) { std::cout << "B& operator=(B&&)" << std::endl; return *this; }
};
int main()
{
    B b1{};
    B b2{b1}; //copy constructor
    return 0;
}

console print :

B()
B(const B&)
~B()
~B()

Second I only define move constructor and move assignment operator. The copy constructor will be implicitly-declared deleted.

#include <iostream>
struct B {
    B() { std::cout << "B()" << std::endl; }
    //~B() { std::cout << "~B()" << std::endl; }

    // B(const B&) { std::cout << "B(const B&)" << std::endl; }
    // B& operator=(const B&) { std::cout << "B& operator=(const B&)" << std::endl; return *this; }

    B(B&&) { std::cout << "B(B&&)" << std::endl; }
    B& operator=(B&&) { std::cout << "B& operator=(B&&)" << std::endl; return *this; }
};
int main()
{
    B b1{};
    B b2{b1}; //compile error
    return 0;
}

The test code will compile error. I think this is the correct, because copy constructor is deleted.

Finally, I only define destructor

#include <iostream>
struct B {
    B() { std::cout << "B()" << std::endl; }
    ~B() { std::cout << "~B()" << std::endl; }

    // B(const B&) { std::cout << "B(const B&)" << std::endl; }
    // B& operator=(const B&) { std::cout << "B& operator=(const B&)" << std::endl; return *this; }

    // B(B&&) { std::cout << "B(B&&)" << std::endl; }
    // B& operator=(B&&) { std::cout << "B& operator=(B&&)" << std::endl; return *this; }
};
int main()
{
    B b1{};
    B b2{b1};
    return 0;
}

The generation of the implicitly-defined copy constructor is deprecated if T has a user-defined destructor. so I think the test code will compile error, but it's correct. WHY???

Aucun commentaire:

Enregistrer un commentaire