1
class demo{
    private:
    int x;
    public:
    demo(int t):x(t) {cout<<"constructor"<<endl;}
    demo(const demo& t):x(t.x) {cout<<"copy constructor"<<endl;}
    demo& operator=(const int& t){
        x=t;
        cout<<"assignment"<<endl;
    }
    demo& operator=(const demo& t){
        x=t.x;
        cout<<"copy assignment"<<endl;
    }
    ~demo()
    {
        cout<<"deconstruction"<<endl;
    }
};
int main()
{
    demo x=2; // if the deconstruct function is called here, then it should be three "deconstruction"
    demo y(2);
    y=3;
}

the code above output two "deconstruction", I suppose it should be three. because "demo x = 2", in my opinion is just like "demo x = demo(2)", so when demo(2) is deconstructed, it should be a "deconstruction" message ouputed. then at the end of the program, x and y is deconstructed. so there should be 3 "deconstruction" output.

Mark_Jing
  • 11
  • 2
  • 4
    your class invokes undefined behaviour, because your assignment operators never return a value – Raildex May 10 '23 at 06:40
  • Do the construction and destruction messages match up? C++ has a rule called "copy elision" that sometimes eliminates a temporary object (removing a pair of copy construction and destruction) – Ben Voigt May 10 '23 at 06:43
  • 3
    @Raildex: `demo x=2;` is "copy-initialization", which has semantics of creating an temporary, then copying it to the final object. But elision is allowed to eliminate the extra object. – Ben Voigt May 10 '23 at 06:44
  • I reviewed your demo a bit to illustrate what happens when: [Demo](http://coliru.stacked-crooked.com/a/a30d07fadabddaf5) – Scheff's Cat May 10 '23 at 06:52
  • @BenVoigt `demo x = 2` is equivalent to `demo x = demo(2)`. In this case, `demo(2)` is a prvalue expression of the same class type (`demo`), so copy elision is mandatory since C++17. https://en.cppreference.com/w/cpp/language/copy_initialization – VLL May 10 '23 at 07:06
  • @BenVoigt `y=3;` is UB – 463035818_is_not_an_ai May 10 '23 at 08:10
  • 3
    @VLL Note that the term _copy elision_ is misleading (though heavily used) in this case since C++17. I think the more precise term is _deferred temporary materialization_. There is an important difference in that for CE, there needs to be a copy/move constructor to be elided. This is not required with DTM (such that it works even with instances of `std::atomic`, where CE does not work). – Daniel Langr May 10 '23 at 08:17

0 Answers0