Why is move-constructor not called? [duplicate] - c++

This question already has answers here:
Why are rvalues references variables not rvalue?
(3 answers)
Closed 1 year ago.
I have the following piece of code:
#include <iostream>
struct T {
int a;
T() = default;
T(T& other) {
std::cout << "copy &\n";
}
T(T&& other) {
std::cout << "move &&\n";
}
};
void foo(T&& x) {
T y(x); // why is copy ctor called??????
}
int main() {
T x;
foo(std::move(x));
return 0;
}
I don't understand why copy constructor is preferred over move constructor even though foo() accepts rvalue-reference.

x is an lvalue itself, even its type is rvalue-reference. Value category and type are two independent properties.
Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;
You need to use std::move to convert it to rvalue, just same as using std::move on x in main().
void foo(T&& x)
{
T y(std::move(x));
}

Related

Understanding perfect forwarding

As I understand rvalue being passed as an argument into function becomes lvalue,
std::forward returns rvalue if argument was passed as rvalue and lvalue if it was passed as lvalue. Here is my class:
#include <string>
#include <iostream>
struct MyClass
{
MyClass()
{
std::cout << "default";
}
MyClass(const MyClass& copy)
{
std::cout << "copy";
}
MyClass& operator= (const MyClass& right)
{
std::cout << "=";
return *this;
}
MyClass& operator= (const MyClass&& right)
{
std::cout << "mov =";
return *this;
}
MyClass(MyClass&& mov)
{
std::cout << "mov constructor";
}
};
void foo(MyClass s)
{
MyClass z = MyClass(std::forward<MyClass>(s));
}
void main()
{
auto a = MyClass();
foo(MyClass()); //z is created by move_constructor
foo(a); //z is created by move_constructor, but I think it must be created using copy constructor
}
My question is: why z variable is created using move_constructor in both cases.
I thought it must be moved in first case foo(MyClass()) and copied in 2nd case foo(a). In second case I pass lvalue as argument s, and std::forward must return lvalue, that is then is passed as lvalue reference into MyClass constructor. Where am I wrong?
I think you are sufficiently confused. The role of forward is only important when universal references come into play, and universal reference is something like T&& t but only when T is a template parameter.
For example, in void foo(X&& x); x is not a forwarding reference, it is a normal rvalue reference, and forwarding it makes no sense. Rather, you use std::move if you want to preserve it's rvalueness, otherwise it becomes an l-value:
void foo(X&& x) {
bar(x); // calls bar with an l-value x, x should be not moved from
baz(std::move(x)); // calls bar with an r-value x, x is likely moved from after this and probably unusable
}
In other words, above function foo was specifically crafted to take rvalue references as it's argument, and will not accept anything else. You, as a function writer, defined it's contract in such way.
In contrast, in a context like template <class T> void foo(T&& t) t is a forwarding reference. Due to reference collapsing rule, it could be an rvalue or an lvalue reference, depending on the valueness of the expression given to the function foo at the call site. In such case, you use
template<class T>
void foo(T&& t) {
// bar is called with value matching the one at the call site
bar(std::forward<T>(t));
}
The type of the argument that you've declared is MyClass. Whatever is the expression that initialises the argument is irrelevant in the case of your function - it does not affect the type of the argument.
MyClass is not a reference type. std::forward converts an lvalue expression of non-reference type to an rvalue. The use of std::forward in this context is equivalent to std::move.
Note that the argument itself is copy-constructed in the call foo(a).

Given a rvalue, why move ctor is a better match than const copy ctor? [duplicate]

This question already has answers here:
What is copy/move constructor choosing rule in C++? When does move-to-copy fallback happen?
(2 answers)
Closed 4 years ago.
Sample code, C++11, -fno-elide-constructors.
#include <iostream>
#include <string>
using namespace std;
class ClassA
{
int a, b;
public:
ClassA() = default;
ClassA(const ClassA &obj)
{
cout << "copy constructor called" << endl;
}
ClassA(ClassA &&obj) {
cout << "move ctor called" << endl;
}
};
ClassA bar(ClassA &str)
{
return str; //call copy ctor
}
int main()
{
ClassA str;
ClassA foo = bar(str); //call move ctor
return 0;
}
https://wandbox.org/permlink/DyALfRETs2LfWSjc
Why this assignment ClassA foo = bar(str); call move ctor instead of copy ctor? Since both const lvalue reference and rvalue reference can accept rvalue.
const lvalue reference can bind to everything, so if the compiler would favor this over the rvalue reference the move constructor would not be called ever if a copy constructor is provided, and that would defeat the purpose of having both.
The rvalue reference accepting function is a more specialized version of the more generic const lvalue reference accepting one, and the compiler always chooses the most specialized version.

C++ move constructor not called [duplicate]

This question already has answers here:
Why do I have to call move on an rvalue reference?
(2 answers)
Rvalue Reference is Treated as an Lvalue?
(4 answers)
Closed 5 years ago.
In the following (borrowed) example, in my environment the move constructor is never called:
#include <iostream>
class MyClass {
public:
MyClass()
{
std::cout << "default constructor\n";
}
MyClass(MyClass& a)
{
std::cout << "copy constructor\n";
}
MyClass(MyClass&& b)
{
std::cout << "move constructor\n";
}
};
void test(MyClass&& temp)
{
MyClass a(MyClass{}); // calls MOVE constructor as expected
MyClass b(temp); // calls COPY constructor...
}
int main()
{
test(MyClass{});
return 0;
}
My output is:
default constructor
default constructor
copy constructor
I use XCode version 9.1, shouldnt the move constructor be called on rvalue references? What am I missing here?
John.
What am I missing here?
The point is that everything that has a name is lvalue.
It means that named rvalue reference itself is lvalue and temp from:
void test(MyClass&& temp)
is lvalue as well. So move constructor is not called.
If you want a move constructor to be called, use std::move:
void test(MyClass&& temp)
{
// ...
MyClass b(std::move(temp)); // use std::move here
}
By the way,
MyClass(MyClass& a)
{
std::cout << "copy constructor\n";
}
is not a copy constructor because copy constructor has a form of:
MyClass(const MyClass& a) { ... }

Difference between && and no ref in return type [duplicate]

This question already has an answer here:
Difference between "return-by-rvalue-ref" & "return-by-value" when you return using std::move?
(1 answer)
Closed 6 years ago.
Is there a difference in behavior when the return type is explicitly declared rvalue vs no ref? According to the example below, there doesn't seem to be any difference.
#include <iostream>
#include <vector>
using namespace std;
struct A {
A(int x) : x_(x) {}
A(A&&) = default; // VC12 hasn't implemented default move
A(const A&) = delete;
A& operator=(A&&) = default;
A& operator=(const A&) = delete;
vector<int> x_;
};
struct B{
B(int x) : a_(x) {}
A&& foo1() { return move(a_); } // explicitly declared as rvalue
A foo2() { return move(a_); } // no ref
A a_;
};
int main() {
B b1(7);
A a1 = b1.foo1();
B b2(7);
A a2 = b2.foo2();
cout << a1.x_.size() << ' ' << a2.x_.size() << endl;
cout << b1.a_.x_.size() << ' ' << b2.a_.x_.size() << endl;
return 0;
}
This example has been compiled by Ideone's C++14 compiler (not sure of the exact version, I suspect it's gnu 5.1) and VC12 (Visual Studio 2013). The only minor difference is VC12 requires an explicit move implementation.
Edit: A related SO post said that the two function end up doing the same thing. However, "in many cases it allows the compiler to perform copy elision and elide the calls to the move constructor of the returned type, as permitted by paragraph 12.8/31 of the C++11 Standard". "Copy elision allows the compiler to create the return value of the function directly in the object."
Question 1: Copy elision should still happen when move is explicitly called, right?
Question 2:
When move is explicitly called on a lvalue (so a required called), A&& and A means the same behavior. When move is not explicitly called, meaning the compiler performs copy elision, A should be the only return type. Combining the two scenario above, can I conclude that return type A&& is not useful and only adds confusion?
With
A&& foo1() { return move(a_); }
A foo2() { return move(a_); }
foo1 returns a (rvalue) reference.
foo2 construct an object A with the move constructor.

Does the inverse of std::move exist? [duplicate]

This question already has answers here:
Function dual to std::move?
(3 answers)
Closed 9 years ago.
std::move can be used to explicitly allow move semantics when the move wouldn't be already allowed implicitly (such as often when returning a local object from a function).
Now, I was wondering (esp. in the context of local return and implicit move there), if there is such a thing as the inverse of std::movethat will prevent moving the object (but still allow copying).
Does this even make sense?
std::move converts an lvalue into an rvalue, and it does this essentially by static_cast. The closest to what I can think of as the opposite are these two type casts:
static_cast<T &>(/*rvalue-expression*/)
static_cast<const T&>(/*rvalue-expression*/)
An example of this can be seen below:
#include <iostream>
void f(const int &)
{ std::cout << "const-lval-ref" << std::endl; }
void f(int &&)
{ std::cout << "rval-ref" << std::endl; }
int main()
{
f(static_cast<const int &>(3));
return 0;
}
Casting the prvalue 3 to const int & ensures that the lvalue-overload of f is chosen.
In most contexts, you get this rvalue-to-lvalue modification automatically, simply by assigning to a variable:
int a = 3;
When you use a after this line, it will be an lvalue. This is true even when a is declared as rvalue reference:
int &&a = 3;
Here, too, a becomes an lvalue (basically because it "has a name").
The only situation where I can imagine an explicit cast to have any relevant effect is my first example above. And there, when dealing with prvalues like 3 or temporaries returned from function calls by copy, the only legal cast is to const-reference (a non-const-reference is not allowed to bind to a prvalue).
The solution to prevent an object to be moved is to make the move constructor of the object private, this way the object can't be moved but can be copied.
Example with move:
enter code here
#include <iostream>
class A {
public:
std::string s;
A() : s("test") {}
A(const A& o) : s(o.s) { std::cout << "move failed!\n";}
A(A&& o) : s(std::move(o.s)) { std::cout << "move was succesfull!\n"; }
};
int main(int argc, const char * argv[])
{
A firsObject;
A secondObject = std::move(firsObject);
return 0;
}
Example with move disabled:
#include <iostream>
class A {
public:
std::string s;
A() : s("test") {}
A(const A& o) : s(o.s) { std::cout << "move failed!\n";}
private:
A(A&& o) : s(std::move(o.s)) { std::cout << "move was succesfull!\n"; }
};
int main(int argc, const char * argv[])
{
A firsObject;
A secondObject = std::move(firsObject);
return 0;
}
template<class T>
T& unmove(T&& t)
{
return t;
}
This will change the value category of the argument expression to an lvalue, no matter what it was originally.
void f(const int&); // copy version
void f(int&&); // move version
int main()
{
int i = ...;
f(42); // calls move version
f(move(i)); // calls move version
f(i); // calls copy version
f(unmove(42)); // calls copy version
f(unmove(move(i))); // calls copy version
f(unmove(i)); // calls copy version
}