Returning a Named Object by Value and Implicit Move Rule
In C , an object can be returned from a function either by reference or by value. When returning by value, the object is copied or moved, depending on the context. The implicit move rule is applied when returning an object by value from a function where the object is temporary.
Example 1: Move Constructor
Consider the example below:
<code class="cpp">class test { public: test(int y) { printf("test(int y)\n"); } test() { printf("test()\n"); } test(const test& z) { printf("test(const test&z)\n"); } test(test&& s)noexcept{ printf("test(test&& s)\n"); } test& operator=(test e) { printf("test& operator=(test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; }</code>
This example returns an object of type test by value with the following constructors:
When the function Some_thing is called, an instance of test is created inside the function by default and then returned. The implicit move rule is applied, and the move constructor test(test&&) is used to move the temporary object into the object returned by the function.
Therefore, the output shows the following steps:
Example 2: Copy Constructor
Now, let's consider this modified example:
<code class="cpp">class test { public: test(int y) { printf("test(int y)\n"); } test() { printf("test()\n"); } test(test& z) { printf("test(test&z)\n"); } test& operator=(test e) { printf("test& operator=(test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; }</code>
In this case, the move constructor test(test&&) is not available. Instead, the copy constructor test(test&) is used to copy the temporary object returned by the function into the object created on the stack in main.
The output shows the following steps:
Example 3: Deleted Move Constructor
Finally, if we explicitly delete the move constructor like this:
<code class="cpp">class test { public: test(test&& z) = delete; test(int y) { printf("test(int y)\n"); } test() { printf("test()\n"); } test(const test& z) { printf("test(test&z)\n"); } test& operator=(test e) { printf("test& operator=(test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; }</code>
The move constructor cannot be used, and the compilation will fail because there is no viable constructor to use for the return value.
In conclusion, the implicit move rule is applied when returning an object of a class by value from a function where the object is temporary. If a move constructor is available, it will be used, but if not, the copy constructor will be used instead. If the move constructor is explicitly deleted, compilation will fail.
The above is the detailed content of When Returning a Named Object by Value in C , Does the Implicit Move Rule Apply?. For more information, please follow other related articles on the PHP Chinese website!