why non-movable Object still a copy - c++

Consider the following code, Entity object is non-movable. I know that std::move(Obj) just cast the Obj to a rvalue reference Obj. And I also know that rvalue reference variable is still a lvalue object. But I still confusing why statement auto temp = std::move(a) can call copy constructor, statement a = std::move(b); can call copy assignment operator. Since, std::move(a) is a rvalue reference, why it can still call lvalue constructor.
#include <iostream>
template<typename T>
void my_swap(T& a, T& b) {
auto temp = std::move(a);
a = std::move(b);
b = std::move(temp);
}
class Entity{
int _id;
public:
Entity(int id) :_id(id) {std::cout << "construtor\n" << std::endl;}
Entity(const Entity& other) {
_id = other._id;
std::cout << "copy constructor\n" << std::endl;
}
Entity& operator= (const Entity& other) {
if (&other == this) return *this;
this->_id = other._id;
std::cout << "copy assignment operator\n";
return *this;
}
};
int main() {
Entity e1 = Entity(10);
Entity e2 = Entity(20);
my_swap(e1,e2);
return 0;
}

Entity object is non-movable
No. Even it doesn't have move constructor/assignment-operator, it has copy constructor/assignment-operator taking lvalue-reference to const. std::move(a) and std::move(b) are rvalue (xvalue) expressions and they could be bound to lvalue-reference to const.
You might also check std::is_move_constructible:
Types without a move constructor, but with a copy constructor that accepts const T& arguments, satisfy std::is_move_constructible.

If you want to make your Entity non-movable, then add the move-constructor and move-assignment operator as deleted:
Entity(Entity&& other) = delete;
Entity& operator= (Entity&& other) = delete;

Considering the following code, Entity object is non-movable.
No, it isn't. Entity is movable.
But I still confusing why statement auto temp = std::move(a)
Lvalue reference to const can be bound to an rvalue. The copy constructor accepts an lvalue reference to const parameter. That parameter can be bound to the std::move(a) rvalue argument.
And I also know that rvalue reference variable is still a lvalue object.
Not quite. References are not objects. An id-expression that names anything, including an rvalue reference varaible, is an lvalue.
Entity is movable. Does is because there exists default move constructor/assignment-operator.
It is movable because it has a copy constructor/assignment operator, and it doesn't have deleted move constructor/assignment operator.

Related

Copy constructor is called instead of move constructor - why?

I have this code, taken from here by the way http://www.cplusplus.com/doc/tutorial/classes2/
// move constructor/assignment
#include <iostream>
#include <string>
#include <utility>
using namespace std;
class Example6
{
string* ptr;
public:
Example6(const string& str) :
ptr(new string(str))
{
cout << "DONT MOVE " << '\n';
}
~Example6()
{
delete ptr;
}
// move constructor
Example6(Example6&& x) :
ptr(x.ptr)
{
cout << "MOVE " << '\n';
x.ptr = nullptr;
}
// move assignment
Example6& operator=(Example6&& x)
{
delete ptr;
ptr = x.ptr;
x.ptr = nullptr;
return *this;
}
// access content:
const string& content() const
{
return *ptr;
}
// addition:
Example6 operator+(const Example6& rhs)
{
return Example6(content() + rhs.content());
}
};
int main()
{
Example6 foo("Exam");
Example6 bar = Example6("ple"); // move-construction
foo = foo + bar; // move-assignment
cout << "foo's content: " << foo.content() << '\n';
return 0;
}
I only added output in constructor to see which is being called. To my surprise it is always the first one, copy constructor. Why does it happen? I did some research and found some info about elision. Is it somehow possible to prevent it and always call move constructor?
Also, as a side note, as I said this code is from cplusplus.com. However, I read about move semantics in some other places and I wonder if this move constructor here is done right. Shouldn't it call
ptr(move(x.ptr))
instead of just
ptr(x.ptr)
The way I understand this, if we use the second option, then we are calling copy constructor of string, instead of move, because x is rvalue reference that has a name, so it is really lvalue and we need to use move to cast it to be rvalue. Do i miss something, or is it really tutorial's mistake?
Btw, adding move doesn't solve my first problem.
So anything with a name is an lvalue.
An rvalue reference with a name is an lvalue.
An rvalue reference will bind to rvalues, but it itself is an lvalue.
So x in ptr(x.ptr) is an rvalue reference, but it has a name, so it is an lvalue.
To treat it as an rvalue, you need to do ptr( std::move(x).ptr ).
Of course, this is mostly useless, as moving a ptr does nothing as ptr is a dumb raw pointer.
You should be following the rule of 0 here.
class Example6 {
std::unique_ptr<string> ptr;
public:
Example6 (string str) : ptr(std::make_unique<string>(std::move(str))) {cout << "DONT MOVE " << '\n';}
Example6():Example6("") {}
~Example6 () = default;
// move constructor
Example6 (Example6&& x) = default;
// move assignment
Example6& operator= (Example6&& x) = default;
// access content:
const string& content() const {
if (!ptr) *this=Example6{};
return *ptr;
}
// addition:
Example6 operator+(const Example6& rhs) {
return Example6(content()+rhs.content());
}
};
because business logic and lifetime management don't belong intermixed in the same class.
While we are at it:
// addition:
Example6& operator+=(const Example6& rhs) & {
if (!ptr) *this = Example6{};
*ptr += rhs.content();
return *this;
}
// addition:
friend Example6 operator+(Example6 lhs, const Example6& rhs) {
lhs += rhs;
return lhs;
}
Copy constructor is called ... - why?
The premise of your question is faulty: The copy constructor is not called. In fact, the class is not copyable.
The first constructor is a converting constructor from std::string. The converting constructor is called because Example6 objects are initialised with a string argument. Once in each of these expressions:
Example6 foo("Exam")
Example6("ple")
Example6(content() + rhs.content()
... instead of move constructor
There are a few copy-initialisations by move in the program. However, all of them can be elided by the compiler.
Is it somehow possible to prevent it and always call move constructor?
There are a few mistakes that can prevent copy elision. For example, if you wrote the addition operator like this:
return std::move(Example6(content()+rhs.content()));
The compiler would fail to elide the move and probably tell you about it if you're lucky:
warning: moving a temporary object prevents copy elision
Shouldn't it call
ptr(move(x.ptr))
instead of just
ptr(x.ptr)
There's no need. Moving a pointer is exactly the same as copying a pointer. Same holds for all fundamental types.
The way I understand this, if we use the second option, then we are calling copy constructor of string, instead of move
ptr is not a string. It is a pointer to a string. Copying a pointer does nothing to the pointed object.
PS. The example program is quite bad quality. There should never be owning bare pointers in C++.
I can say your class does not have a copy constructor.
Because copy ctor parameter have to be const and reference
class Example6{
public:
Example6(const Example6 &r);
};

Why does the compiler choose the copy ctor after calling move

For the following code, I know that because I implement a copy constructor the default move is blocked by the compiler, what I don't understand is why the compiler choose the copy constructor, and not issuing an error?
Can a rvalue reference be the parameter for a reference function if no rvalue ref function exists?
If not, what do happens here?
#include <iostream>
using namespace std;
class A{
public:
A(){printf("constructor\n");}
A(const A& a){printf("copy constructor");}
};
int main()
{
A a;
A b = std::move(a);
return 1;
}
The output is:
constructor
copy constructor
Thanks
The reason is that rvalue expressions can be bound to function parameters that are const lvalue references.
Also note that const rvalue expressions cannot be bound to rvalue references:
class A{
public:
A(){printf("constructor\n");}
A(const A& a){printf("copy constructor");}
A(A&&) = default; // <-- has move ctor
};
int main()
{
const A a; // <-- const!
A b = std::move(a); // <-- copy not move!!!
return 1;
}
The code above still calls the copy constructor, even though there is a move constructor.
std::move will take your named value and turn it into an rvalue expression, nothing more.
And, just like for any other rvalue, if it can't be moved, it'll be copied.
An rvalue of type T can be bound to a const T& just fine.

Move-ctor and copy-ctor not called

Let's take the following C++ sample:
#include <iostream>
struct X
{
std::string s;
X() : s("X") { }
X(const X& other) : s{other.s} { std::cout << "cpy-ctor\n"; }
X(X&& o): s{o.s} { o.s = ""; std::cout << "move-ctor\n"; }
X& operator=(const X& other) {
std::cout << "cpy-assigned\n";
s = other.s;
return *this;
}
X& operator=(X&& other) {
if (this != &other) {
s = other.s;
other.s = "";
}
std::cout << "move assigned\n";
return *this;
}
};
X f(X x) {
std::cout << "f: ";
return x;
}
X g() {
std::cout << "g: ";
X x;
return x;
}
int main() {
X x;
X y;
x = f(X());
y = g();
}
If I compile it with gcc 4.8.2, I have the following result:
f: move-ctor
move assigned
g: move assigned
I do not understand why copy-constructor is not called when I am calling the g function.
I am just trying to understand when the copy or the move constructors are called.
Although you are correct to identify that there is, logically, a copy/move of the local variable x from inside g() when it is returned, a useful feature of C++ is that it can elide (i.e. skip) this operation in many cases, even when the copy/move would have side-effects. This is one of those cases. When performed, this is known as the named return value optimisation.
It's arguably less useful than it was before we had move semantics, but it's still nice to have. Indeed, C++17 made it mandatory in some (select) cases.
In C++ all the expressions are:
lvalue
prvalue
xvalue
Constructing an object
- lvalue
Y x{};
Y y{x}; // copy constructor, x is an lvalue
- prvalue - RVO
With RVO, which is enabled by gcc by default. This elides using the copy constructor and instead the object is constructed once.
X g()
{
X x {};
x.value = 10;
return x;
}
X y {g()}; // X constructor get's called only once to create "y". Also
// y is passed a a reference to g() where y.value = 10.
// No copy/move constructor for optimization "as if" rule
- prvalue - No RVO
Without RVO, in this case it depends. If the move constructors are explicitly or implicitly deleted, then it will call the copy constructor
Copy constructor
struct X { X(const X&) {}}; // implicitly deletes move constructor
// and move assignment, see rule of 5
X g()
{
return X{}; // returns a prvalue
}
X y {g()}; // prvalue gets converted to xvalue,
// "temporary materialization", where the xvalue has an
// identity where members can be copied from. The xvalue
// binds to lvalue reference, the one from copy constructor
// argument
Move constructor
X { X(X&&) {}}; // explicitly declared move constructor
X g()
{
return X{}; // returns a prvalue
}
X y {g()}; // prvalue gets converted to xvalue,
// "temporary materialization", where the xvalue has an
// identity where members can be moved from. The xvalue
// binds to rvalue reference, the one from move constructor
// argument
- xvalue
X x {};
X y {std::move(x)}; // std::move returns an xvalue, where if move
// constructor is declared will call it, other wise
// copy constructor, similar to explained above for
// prvalue.
Copy/move assignment
- lvalue
X x{};
X y{};
x = y; // call copy assignment operator since y is an lvalue.
- prvalue
If the move assignments are explicitly or implicitly deleted, then it will call the copy assignment operator.
Copy assignment
struct X{ X& operator=(const X&); } // implicilty deletes move
// constructor and move assignment,
// see rule of 5
X g()
{
return X{}; // returns a prvalue
}
x = g(); // prvalue gets converted to xvalue,
// "temporary materialization", where the xvalue has an identity
// where members can be copied from. The xvalue binds to lvalue
// reference, the one from copy assignment operator argument
Move assignment
struct X{ X& operator=(X&&); } // explicitly declared move assignment operator
X g()
{
return X{}; // returns a prvalue
}
x = g(); // prvalue gets converted to xvalue,
// "temporary materialization", where the xvalue has an identity
// where members can be moved from. The xvalue binds to rvalue
// reference, the one from move assignment operator argument
- xvalue
X x {};
X y {};
x = std::move(x); // std::move returns an xvalue, where if move
// assignment is declared will call it, other
// wise copy assignment, similar to explained
// above for prvalue.
A copy constructor is called when you instantiate an object using another object of the same type.
For example:
X x;
X y(x);
The last line in your code assigns a value returned from a function to an already constructed object. This is done via move assignment.

Why I can't move this vector in the copy constructor of my custom class?

class TestClass
{
public:
TestClass(){
cout<<"constructor"<<endl;
p = {1,2,3};
cout<<(unsigned int *)(this->p.data())<<endl;
}
TestClass(const TestClass& test): p(std::move(test.p))
{
cout <<"copy constructor"<<endl;
cout<<(unsigned int *)(this->p.data())<<endl;
}
TestClass(TestClass && test): p(std::move(test.p))
{
cout <<"move constructor"<<endl;
cout<<(unsigned int *)(this->p.data())<<endl;
}
private:
std::vector<int> p;
};
int main()
{
TestClass t{};
TestClass p{t};
TestClass s{std::move(p)};
return 0;
}
And the output is
constructor
0xb92bf0
copy constructor
0xb915b0
move constructor
0xb915b0
I am just wondering why the address below constructor is different from the one below copy constructor. From what I understand, even it is a copy constructor, but I used std::move to get a rvalue reference and vector's move constructor should be called, so they should be same object.
std::move just casts whatever is passed to it to an xvalue, so rvalue-references can bind to it and may steal its resources. Here:
TestClass(const TestClass& test): p(std::move(test.p))
std::move will produce an expression of type const std::vector<int> &&, which, as you can see, has a const qualifier. If you check the copy- and move-constructors of std::vector on [vector], you'll see that the move-constructor expects an expression of type std::vector<T> &&, and the copy-constructor expects a const std::vector<T> &:
vector(const vector& x);
vector(vector&&) noexcept;
Compare the result of std::move(test.p) to these two constructors. Because an rvalue-reference doesn't bind to types with const qualifiers (unless the rvalue-reference is const-qualified), then the move-constructor overload isn't a good candidate. The other candidate (copy-constructor) does accept a const-qualified type, and since xvalues have the same properties as rvalues:
http://en.cppreference.com/w/cpp/language/value_category#rvalue
An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
, the copy-constructor is a good candidate and is selected.

Move and Forward cases use

I followed this tutorial to start to understand the move semantics and rvalue references in C++11.
At some point, he implements these two classes with the std::move in the move constructors explaining that
we pass the temporary to a move constructor, and it takes on new life
in the new scope. In the context where the rvalue expression was
evaluated, the temporary object really is over and done with. But in
our constructor, the object has a name; it will be alive for the
entire duration of our function. In other words, we might use the
variable other more than once in the function, and the temporary
object has a defined location that truly persists for the entire
function. It's an lvalue in the true sense of the term locator value
class MetaData
{
public:
MetaData(int size, const string& name)
: _name(name)
, _size(size)
{}
MetaData(const MetaData& other)
: _name(other._name)
, _size(other._size)
{
cout << "MetaData -- Copy Constructor" << endl;
}
MetaData(MetaData&& other)
: _name(move(other._name))
, _size(other._size)
{
cout << "MetaData -- Move Constructor" << endl;
}
~MetaData()
{
_name.clear();
}
string getName() const { return _name; }
int getSize() const { return _size; }
private:
string _name;
int _size;
};
class ArrayWrapper
{
public:
ArrayWrapper()
: _p_vals(new int[64])
, _metadata(64, "ArrayWrapper")
{}
ArrayWrapper(int n)
: _p_vals(new int[n])
, _metadata(n, "ArrayWrapper")
{}
ArrayWrapper(ArrayWrapper&& other)
: _p_vals(other._p_vals)
, _metadata(move(other._metadata))
{
cout << "ArrayWrapper -- Move Constructor" << endl;
other._p_vals = nullptr;
}
ArrayWrapper(const ArrayWrapper& other)
: _p_vals(new int[other._metadata.getSize()])
, _metadata(other._metadata)
{
cout << "ArrayWrapper -- Copy Constructor" << endl;
for (int i = 0; i < _metadata.getSize(); ++i)
_p_vals[i] = other._p_vals[i];
}
~ArrayWrapper()
{
delete[] _p_vals;
}
int* getVals() const { return _p_vals; }
MetaData getMeta() const { return _metadata; }
private:
int* _p_vals;
MetaData _metadata;
};
In the ArrayWrapper move constructor I tried to change std::move with std::forward<MetaData> and the code shows that if I call the ArrayWrapper move constructor this will call the MetaData move constructor, like the example with the std::move.
Of course if I don't use either std::move or std::forward the MetaData copy costructor will be called.
The question is, in this case, is there a difference between using std::move and std::forward? Why should I use one instead of the other?
is there a difference between using std::move and std::forward? Why should I use one instead of the other?
Yes, std::move returns an rvalue reference of its parameter, while std::forward just forwards the parameter preserving its value category.
Use move when you clearly want to convert something to an rvalue. Use forward when you don't know what you've (may be an lvalue or an rvalue) and want to perfectly forward it (preserving its l or r valueness) to something. Can I typically/always use std::forward instead of std::move? is a question you might be interested in here.
In the below snippet, bar would get exactly what the caller of foo had passed, including its value category preserved:
template <class T>
void foo(T&& t) {
bar(std::forward<T>(t));
}
Don't let T&& fool you here - t is not an rvalue reference. When it appears in a type-deducing context, T&& acquires a special meaning. When foo is instantiated, T depends on whether the argument passed is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U. See this excellent article for details. You need to understand about value categories and reference collapsing to understand things better in this front.
The relevant std::forward and std::move declarations are:
template< class T >
T&& forward( typename std::remove_reference<T>::type& t );
template< class T >
typename std::remove_reference<T>::type&& move( T&& t );
For the former:
std::forward<MetaData>(other._metadata);
std::forward<MetaData> returns MetaData&&.
For the latter:
std::move(other._metadata);
//argument derived as lvalue reference due to forwarding reference
std::move<MetaData&>(other._name);
std::move<MetaData&> returns typename std::remove_reference<MetaData&>::type&&, which is MetaData&&.
So the two forms are identical for your example. However, std::move is the right choice here, as it shows our intent to unconditionally move the argument. std::forward can be used to unconditionally move, but the purpose of it is to perfect-forward its argument.