When I read about copy constructor and copy assignment constructor, what I understood is that both gives away their properties one to another, and that both of them are declared implicitly by compiler (if not defined). So both must be exist whether doing something useful or not.
Then I tested this code:
#include <iostream>
using namespace std;
class Test {
public:
Test () {
cout << "Default constructor" << endl;
}
Test (const Test& empty) {
cout << "Copy constructor" << endl;
}
Test& operator=(const Test& empty) {
cout << "Copy assignment operator" << endl;
}
private:
};
int main () {
Test a; // Test default constructor
Test b (a); // Test copy constructor
Test c = b; // Test copy assignment constructor
system ("pause");
return 0;
}
But it seems the copy assignment operator is not called at all. I tried with three conditions:
Everything included. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why not prints out "Copy assignment operator"?
Whitout copy assignment operator just copy constructor. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
Whitout copy constructor just copy assignment operator. It prints out:
// Default constructor # Why "Copy assignment operator" is not printed out?
Only constructor. It prints out:
// Default constructor # Understandable
So, it's like the compiler doesn't even care if I define the copy assignment operator or not. None of the four examples above prints out "Copy assignment operator". So when did it get called, if it is really exists and has a meaning?
Test c = b is an initialization, not an assignment.
If you had done this:
Test c;
c = b;
Then it would have called the copy assignment operator.
Related
I am trying to get the grasp of rvalue references and move semantics with a simple self-made example but I can't understand a specific part. I have created the following class:
class A {
public:
A(int a) {
cout << "Def constructor" << endl;
}
A(const A& var) {
cout << "Copy constructor" << endl;
}
A(A&& var) {
cout << "Move constructor" << endl;
}
A& operator=(const A& var) {
cout << "Copy Assignment" << endl;
return *this;
}
A& operator=(A&& var) {
cout << "Move Assignment" << endl;
return *this;
}
};
I tried the following experiments to see if I can predict how the constructors/operators are going to be called:
A a1(1) - The default constructor is going to be called.
PREDICTED.
A a2 = a1 - The copy constructor is going to be called. PREDICTED.
a1 = a2 - The copy assignment operator is going to be called.
PREDICTED.
Now, I created a simple function that just returns an A object.
A helper() {
return A(1);
}
A a3 = helper() - The default constructor is going to be called in
order to create the object that the helper returns. The move
constructor is not going to be called due to RVO. PREDICTED.
a3 = helper() - The default constructor is going to be called in
order to create the object that the helper returns. Then, the move
assignment operator is going to be called. PREDICTED.
Now comes the part I don't understand. I created another function that is completely pointless. It takes an A object by value and it just returns it.
A helper_alt(A a) {
return a;
}
A a4 = helper_alt(a1) - This will call the copy constructor, to
actually copy the object a1 in the function and then the move
constructor. PREDICTED.
a4 = helper_alt(a1) - This will call the copy constructor, to
actually copy the object a1 in the function and then I thought that
the move assignment operator is going to be called BUT as I saw,
first, the move constructor is called and then the move assignment
operator is called. HAVE NO IDEA.
Please, if any of what I said is wrong or you feel I might have not understood something, feel free to correct me.
My actual question: In the last case, why is the move constructor being called and then the move assignment operator, instead of just the move assignment operator?
Congratulations, you found a core issue of C++!
There are still a lot of discussions around the behavior you see with your example code.
There are suggestions like:
A&& helper_alt(A a) {
std::cout << ".." << std::endl;
return std::move(a);
}
This will do what you want, simply use the move assignment but emits a warning from g++ "warning: reference to local variable 'a' returned", even if the variable goes immediately out of scope.
Already other people found that problem and this is already made a c++ standard language core issue
Interestingly the issue was already found in 2010 but not solved until now...
To give you an answer to your question "In the last case, why is the move constructor being called and then the move assignment operator, instead of just the move assignment operator?" is, that also C++ committee does not have an answer until now. To be precise, there is a proposed solution and this one is accepted but until now not part of the language.
From: Comment Status
Amend paragraph 34 to explicitly exclude function parameters from copy elision. Amend paragraph 35 to include function parameters as eligible for move-construction.
consider the below example. I have compiled the sample code using -fno-elide-constructors flag to prevent RVO optimizations:
g++ -fno-elide-constructors -o test test.cpp
#include<iostream>
using namespace std;
class A {
public:
A(int a) {
cout << "Def constructor" << endl;
}
A(const A& var) {
cout << "Copy constructor" << endl;
}
A(A&& var) {
cout << "Move constructor" << endl;
}
A& operator=(const A& var) {
cout << "Copy Assignment" << endl;
return *this;
}
A& operator=(A&& var) {
cout << "Move Assignment" << endl;
return *this;
}
};
A a_global(1);
A helper_alt(A a) {
return a;
}
A helper_a_local(A a) {
A x(1);
return x;
}
A helper_a_global(A a) {
return a_global;
}
int main(){
A a1(1);
A a4(4);
std::cout << "================= helper_alt(a1) ==================" << std::endl;
a4 = helper_alt(a1);
std::cout << "=============== helper_a_local() ================" << std::endl;
a4 = helper_a_local(a1);
std::cout << "=============== helper_a_global() ================" << std::endl;
a4 = helper_a_global(a1);
return 0;
}
This will result in the below output:
Def constructor
Def constructor
Def constructor
================= helper_alt(a1) ==================
Copy constructor
Move constructor
Move Assignment
=============== helper_a_local() ================
Copy constructor
Def constructor
Move constructor
Move Assignment
=============== helper_a_global() ================
Copy constructor
Copy constructor
Move Assignment
In simple words, C++ constructs a new temporary object (rvalue) when the return type is not a reference, which results in calling Move or Copy constructor depending on the value category and the lifetime of the returned object.
Anyway, I think the logic behind calling the constructor is that you are not working with reference, and returned identity should be construed first, either by copy or move constructor, depending on the returned value category or lifetime of the return object. As another example:
A helper_move_vs_copy(A a) {
// Call the Copy Constructor
A b = a;
// Call the Move Constructor, Due to the end of 'a' lifetime
return a;
}
int main(){
A a1(1);
A a2(4);
std::cout << "=============== helper_move_vs_copy() ================" << std::endl;
helper_move_vs_copy(a1);
return 0;
}
which outputs:
Def constructor
Def constructor
=============== helper_move_vs_copy() ================
Copy constructor
Copy constructor
Move constructor
From cppreference:
an xvalue (an “eXpiring” value) is a glvalue that denotes an object whose resources can be reused;
At last, it is the job of RVO to decrease unnecessary moves and copies by optimization of the code, which can even result in an optimized binary for basic programmers!
For some time this has been confusing me. And I've not been able to find a satisfactory answer thus far. The question is simple. When does a move assignment operator get called, and when does a move constructor operator get called?
The code examples on cppreference.com yield the following interesting results:
The move assignment operator:
a2 = std::move(a1); // move-assignment from xvalue
The move constructor:
A a2 = std::move(a1); // move-construct from xvalue
So has it do to with which is implemented? And if so which is executed if both are implemented? And why is there the possibility of creating a move assignment operator overload at all, if it's identical anyway.
A move constructor is executed only when you construct an object. A move assignment operator is executed on a previously constructed object. It is exactly the same scenario as in the copy case.
Foo foo = std::move(bar); // construction, invokes move constructor
foo = std::move(other); // assignment, invokes move assignment operator
If you don't declare them explicitly, the compiler generates them for you (with some exceptions, the list of which is too long to be posted here).
See this for a complete answer to when the move member functions are implicitly generated.
When does a move assignment operator get called
When you assign an rvalue to an object, as you do in your first example.
and when does a move constructor operator get called?
When you initialise an object using an rvalue, as you do in your second example. Although it isn't an operator.
So has it do to with which is implemented?
No, that determines whether it can be used, not when it might be used. For example, if there's no move constructor, then construction will use the copy constructor if that exists, and fail (with an error) otherwise.
And if so which is executed if both are implemented?
Assignment operator for assignment, constructor for initialisation.
And why is there the possibility of creating a move assignment operator overload at all, if it's identical anyway.
It isn't identical. It's invoked on an object that already exists; the constructor is invoked to initialise an object which previously didn't exist. They often have to do different things. For example, assignment might have to delete something, which won't exist during initialisation.
This is the same as normal copy assignment and copy construction.
A a2 = std::move(a1);
A a2 = a1;
Those call the move/copy constructor, because a2 doesn't yet exist and needs to be constructed. Assigning doesn't make sense. This form is called copy-initialization.
a2 = std::move(a1);
a2 = a1;
Those call the move/copy assignment operator, because a2 already exists, so it doesn't make sense to construct it.
Move constructor is called during:
initialization: T a = std::move(b); or T a(std::move(b));, where b is of type T;
function argument passing: f(std::move(a));, where a is of type T and f is void f(T t);
Move assignment operation is called during:
function return: return a; inside a function such as T f(), where a is of type T which has a move constructor.
assignment
The following example code illustrates this :
#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class A {
public :
A() { cout << "constructor called" << endl;}
~A() { cout << "destructor called" << endl;}
A(A&&) {cout << "move constructor called"<< endl; return;}
A& operator=(A&&) {cout << "move assignment operator called"<< endl; return *this;}
};
A fun() {
A a; // 5. constructor called
return a; // 6. move assignment operator called
// 7. destructor called on this local a
}
void foo(A){
return;
}
int main()
{
A a; // 1. constructor called
A b; // 2. constructor called
A c{std::move(b)}; // 3. move constructor called
c = std::move(a); // 4. move assignment operator called
a = fun();
foo(std::move(c)); // 8. move constructor called
}
Output :
constructor called
constructor called
move constructor called
move assignment operator called
constructor called
move assignment operator called
destructor called
move constructor called
destructor called
destructor called
destructor called
destructor called
When I read about copy constructor and copy assignment constructor, what I understood is that both gives away their properties one to another, and that both of them are declared implicitly by compiler (if not defined). So both must be exist whether doing something useful or not.
Then I tested this code:
#include <iostream>
using namespace std;
class Test {
public:
Test () {
cout << "Default constructor" << endl;
}
Test (const Test& empty) {
cout << "Copy constructor" << endl;
}
Test& operator=(const Test& empty) {
cout << "Copy assignment operator" << endl;
}
private:
};
int main () {
Test a; // Test default constructor
Test b (a); // Test copy constructor
Test c = b; // Test copy assignment constructor
system ("pause");
return 0;
}
But it seems the copy assignment operator is not called at all. I tried with three conditions:
Everything included. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why not prints out "Copy assignment operator"?
Whitout copy assignment operator just copy constructor. It prints out:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
Whitout copy constructor just copy assignment operator. It prints out:
// Default constructor # Why "Copy assignment operator" is not printed out?
Only constructor. It prints out:
// Default constructor # Understandable
So, it's like the compiler doesn't even care if I define the copy assignment operator or not. None of the four examples above prints out "Copy assignment operator". So when did it get called, if it is really exists and has a meaning?
Test c = b is an initialization, not an assignment.
If you had done this:
Test c;
c = b;
Then it would have called the copy assignment operator.
class WithCC {
public:
WithCC() {}
WithCC(const WithCC&) {
cout << "in WithCC's copy constructor" << endl;
}
};
class Composite {
WithCC withcc; // Embedded objects
public:
Composite() {}
};
int main() {
Composite c;
Composite c2 = c;
}
With the code above, withcc's copy constructor gets called and I get the output:
in WithCC's copy constructor
But if I add a copy constructor to Composite like this...
class Composite {
WithCC withcc; // Embedded objects
public:
Composite() {}
Composite(const Composite&) {
cout << "in composite's copy constructor" << endl;
}
};
withcc's copy constructor doesn't seem to get called because the output is:
in composite's copy constructor
Why isn't withcc's copy constructor called here?
In the first sample you omitted a copy constructor for Composite and hence C++ generated a default one for you. This default one essentially runs a field by field copy and hence was running the copy constructor of WithCC.
When you explicitly defined a copy constructor C++ does no magic. It is up to you to copy the fields as necessary. For example
Composite(const Composite& other) : withcc(other.withcc) {
cout << "in composite's copy constructor" << endl;
}
The copy constructor implicitly defined by the compiler performs a memberwise copy/move of its bases and members.
A user-defined copy-constructor defaault initializes subobjects of the derived class if their constructors were not called explicitly in the ctor-list.
So in your last code snippet you defined explicitly the copy constructor
Composite(const Composite&) {
cout << "in composite's copy constructor" << endl;
}
but its ctor list is empty. So data member withcc will be default initialized.
I described this more detailed in my article
Implicitly defined copy constructor and explicitly defined copy constructor: what is the difference?
Though it is written in Russian but you will be able to read it using for example google service translare.
I'm having difficulty wrapping my mind around the following (specifically, scenario b):
(Assume I have defined an assignment operator, addition operator, and copy constructor just to output the fact that they are being called)
scenario a:
Simple a;
Simple b;
Simple c = a + b;
The output is as follows:
Simple constructor called
Simple constructor called
Simple add operator call
Simple constructor called
copy constructor called
-- This is all fine and dandy
scenario b (the behavior that I cannot understand):
Simple d;
Simple e;
Simple f;
f = d + e;
Simple constructor called
Simple constructor called
Simple constructor called
Simple add operator called
Simple constructor called
copy constructor called
assignment operator called
The question that I have is that in scenario b, why is the copy constructor called right before the assignment operator is? To my understanding, a copy constructor will only be called on an uninitialized object. However, in this scenario, the object f has been initialized in the line preceding the addition.
An explanation would be greatly appreciated.
Apologies for not posting the source code right away (and for the lack of indentation - I am having problems copying to the textarea). Here it is in all of it's simplicity.
I am using Visual Studio 2005. Unfortunately, I am not that familiar with the workings of it yet, hence I cannot specify the optimization parameters that are being passed to the compiler.
class Simple
{
public:
Simple(void);
Simple operator +(const Simple& z_Simple) const;
Simple& operator =(const Simple& z_Simple);
Simple(const Simple& z_Copy);
int m_Width;
int m_Height;
public:
~Simple(void);
};
#include "Simple.h"
#include <iostream>
using std::cout;
using std::endl;
Simple::Simple(void)
{
this->m_Height = 0;
this->m_Width = 0;
cout << "Simple constructor called" << endl;
}
Simple::Simple(const Simple& z_Copy)
{
cout << "copy constructor called" << endl;
this->m_Height = z_Copy.m_Height;
this->m_Width = z_Copy.m_Width;
}
Simple& Simple::operator =(const Simple &z_Simple)
{
cout << "assignment operator called" << endl;
this->m_Height = z_Simple.m_Height;
this->m_Width = z_Simple.m_Width;
return *this;
}
Simple Simple::operator +(const Simple &z_Simple) const
{
cout << "Simple add operator called" << endl;
int y_Height = this->m_Height + z_Simple.m_Height;
int y_Width = this->m_Width + z_Simple.m_Width;
Simple y_Ret;
y_Ret.m_Height = y_Height;
y_Ret.m_Width = y_Width;
return y_Ret;
}
Simple::~Simple(void)
{
cout << "destructor called" << endl;
}
Certainly Nemo's explanation is the one that my novice C++ mind can grasp :)
After changing the optimization level to /O2, I can see the output of scenario b as follows (and what I would have expected)
Simple constructor called
Simple constructor called
Simple constructor called
Simple add operator called
Simple constructor called
assignment operator called
Thank you all for your suggestions.
Your + operator returns a object by value, which might result in call to copy constructor if the compiler did not elide it.
Simple Simple::operator +(const Simple &z_Simple) const
{
//......
Simple y_Ret;
//......
return y_Ret;
}
Code:
Simple d;
Simple e;
Simple f;
f = d + e;
Here is a step by step analysis:
Simple constructor called ---> creation of `d`
Simple constructor called ---> creation of `e`
Simple constructor called ---> creation of `f`
Simple add operator called ---> Inside Addition operator
Simple constructor called ---> creation of local `y_Ret`
copy constructor called ---> `y_Ret` returned by value
assignment operator called ---> Result returned by `+` used for `=`