std::tuple for non-copyable and non-movable object

前端 未结 2 1872
醉酒成梦
醉酒成梦 2021-02-15 13:56

I have a class with copy & move ctor deleted.

struct A
{
    A(int a):data(a){}
    ~A(){ std::cout << \"~A()\" << this << \" : \" <<         


        
2条回答
  •  无人共我
    2021-02-15 14:24

    Your problem is that you explicitly asked for a tuple of rvalue references, and a rvalue reference is not that far from a pointer.

    So auto q = std::tuple(A{100},A{200}); creates two A objects, takes (rvalue) references to them, build the tuple with the references... and destroys the temporary objects, leaving you with two dangling references

    Even if it is said to be more secure than good old C and its dangling pointers, C++ still allows programmer to write wrong programs.

    Anyway, the following would make sense (note usage of A& and not A&&):

    int main() {
        A a(100), b(100); // Ok, a and b will leave as long as main
        auto q = tuple(a, b);  // ok, q contains references to a and b
        ...
        return 0; // Ok, q, a and b will be destroyed
    }
    

提交回复
热议问题