Using Move Semantics In Own Code

Using String: class Person

  • Idea: constructor taking person’s firstname and lastname

  • Passing temporaries right into members ⟶ implement move constructor

#ifndef PERSON_H
#define PERSON_H

#include "string-30.h"

struct Person
{
    Person(String&& firstname, String&& lastname)
    : firstname(firstname), 
      lastname(lastname) {}

    String firstname;
    String lastname;
};

#endif
#include <gtest/gtest.h>
#include <cstring>

#include "person-10.h"

TEST(person_suite, bogus)
{
    Person p("Joerg", "Faschingbauer");  // <--- temporary String object -> move ctor

    ASSERT_EQ(strcmp(p.firstname.c_str(), "Joerg"), 0);
    ASSERT_EQ(strcmp(p.lastname.c_str(), "Faschingbauer"), 0);
}
code/person-10.h:9:7: error: use of deleted function ‘String::String(const String&)’
    9 |     : firstname(firstname), lastname(lastname) {}
      |       ^~~~~~~~~~~~~~~~~~~~

What?

Using Rvalue References Inside Function: std::move

#ifndef PERSON_H
#define PERSON_H

#include "string-30.h"

struct Person
{
    Person(String&& firstname, String&& lastname)   // <--- parameters have names -> lvalues
    : firstname(std::move /*!!*/ (firstname)),      // <--- request String's move contructor
      lastname(std::move /*!!*/ (lastname)) {}

    String firstname;
    String lastname;
};

#endif