samedi 4 février 2017

why should we use std::move semantic with unique pointers?

Conceptual Question

Say we have simple example like this:

 void foo(std::unique_ptr<int> ptr)
    {
        std::cout << *ptr.get() << std::endl;
    }
    int main()
    {
        std::unique_ptr<int> uobj = std::make_unique<int>(4);
        foo(uobj );  // line-(1) Problem ,but Alternative -> foo(std::move(uobj ))
        std::unique_ptr<int> uobjAlt = uobj; // line-(2) Problem ,but Alternative -> std::unique_ptr<int> uobjAlt = std::move(uobj);        
        return EXIT_SUCCESS;
    }

We know simply std::unique_ptr bound with concept of resource owning by single owner with moving resource among multiple owners while shared_ptr has opposite aspect. As example shown above, when you look at line-(1) & line-(2) you notice that some standard rules are being violated because std::unique_ptr has(deleted) no both copy constructors and copy assignable operators defined, but In order to avoid compilation errors we have to use std::move function instead.

Problem

Why modern C++ compiler cannot automatically generate instructions to move the resource among unique pointers in line-(1) and line-(2)? because we know unique pointer intentionally design for that. Why should we use std::move explicitly to instruct the machine to move ownership of the resource?

std::unique_ptr nothing but class template.we know that, But situations addressed in line-1 and line -2 having issues while compiler complain about copying unique_pointers not allowed(deleted functions).why we having these kind of errors why c++ standard and compiler vendors cannot override this concept?

Unique Pointer intentionally designed for the purpose of moving resource while passing its ownership, when we pass it as function/constructor argument or assign to another unique pointer, it conceptually should move resource with ownership nothing else, but why we should use std::move to convey compiler to actual move, why don't we have a freedom to call line-(1) and line-(2) as it is? (while intelligent compiler generate automatic move operation among unique pointers for us, unless there is const or non-const reference passing).

(Sorry for long description and broken English) Thank you.

Aucun commentaire:

Enregistrer un commentaire