0

我已经逐步完成了这段代码,但不明白为什么移动构造函数被调用 4 次而不是 1 次。不应该只调用一次吗?我已经在 Mac 上使用 CLion 逐步完成了代码。这是控制台上的结果:

Vehicle #0 Default constructor called

Vehicle #1 Initializing constructor called

Vehicle #0 move constructor called

Vehicle #0 move constructor called

Vehicle #0 move constructor called

Vehicle #0 move constructor called

Process finished with exit code 11

这是代码:

#include <iostream>
#include <thread>
#include <future>
#include <memory>

class Vehicle
{
public:
    //default constructor
    Vehicle() : _id(0), _name(new std::string("Default Name"))
{
    std::cout << "Vehicle #" << _id << " Default constructor called" << std::endl;
}

//initializing constructor
Vehicle(int id, std::string name) : _id(id), _name(new std::string(name))
{
    std::cout << "Vehicle #" << _id << " Initializing constructor called" << std::endl;
}

// move constructor with unique pointer
Vehicle(Vehicle && src) : _name(std::move(src._name))
{
    // move id to this and reset id in source
    _id = src.getID();
    src.setID(0);

    std::cout << "Vehicle #" << _id << " move constructor called" << std::endl;
};

// setter and getter
void setID(int id) { _id = id; }
int getID() { return _id; }
void setName(std::string name) { *_name = name; }
std::string getName() { return *_name; }

private:
   int _id;
    std::unique_ptr<std::string> _name;
};


int main()
{
    // create instances of class Vehicle
    Vehicle v0;    // default constructor
    Vehicle v1(1, "Vehicle 1"); // initializing constructor

    // launch a thread that modifies the Vehicle name
    std::future<void> ftr = std::async([](Vehicle v) {
        v.setName("Vehicle 2");
    },std::move(v0)); // move constructor only called here?

    ftr.wait();
    std::cout << v0.getName() << std::endl; // this will now cause an exception

return 0;
}
4

0 回答 0