When should I use a move contructor?

closed account (Ey80oG1T)
So I now a copy constructor can help us find rvalues in code. So should I use it here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Example
{
  Example(std::string&& example);
}

// does the copy constructor pick this up?
Example("Hello World!");

// what about this? or do I have to have another constructor for this?
std::string s = "Hi";
Example(s);

// or this?
Example e(std::string("Hey"));


What are the best practices for it? Thanks
Last edited on
I would need to see all the constructors for Example to be able to answer your questions.
closed account (Ey80oG1T)
Oh, so if I had something like this:

1
2
3
4
5
6
class Example
{
public:
  Example(std::string example);
  Example(std::string&& example);
}


Is the copy constructor used for taking a rvalue?
Those aren't copy ctors.
They are just plain old ctors.
A copy ctor takes a reference to an object of the type being constructed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;

class Example
{
    string s;

public:
    Example() = default;

    Example(const string& s) : s(s) { }

    Example(Example& e)    // copy constructor
    {
        s = e.s;
    }

    Example(Example&& e)   // move constructor
    {
        s = move(e.s);
    }

    friend ostream& operator<<(ostream& out, const Example& e)
    {
        return out << e.s;
    }
};

int main()
{
    auto prn {[](auto s, auto x){ cout << s << ": " << x << '\n'; }};

    Example e("hello");
    Example f(e);
    prn('e', e);
    prn('f', f);

    Example g(move(e));    
    prn('e', e);  // e will be the empty string here
    prn('g', g);
}

Last edited on
Is the copy constructor used for taking a rvalue?
No. Example still supplies both a copy and move constructor - they're provided implicitly by the compiler.

Example's implicit move constructor, whose signature is
Example::Example(Example&&)
would be preferred over its implicit copy constructor, whose signature is
Example::Example(Example const&)
when the argument expression is a non-const rvalue expression.

Last edited on
Topic archived. No new replies allowed.