【发布时间】:2020-08-29 12:31:20
【问题描述】:
想法是使用移动语义来避免不必要的复制。 给定以下代码:
#include <iostream>
#include <string>
#include <utility>
class Address {
private:
const std::string m_street;
const std::string m_city;
const int m_suite;
public:
Address(const std::string &street, const std::string &city, int suite) : m_street {std::move(street)},
m_city {std::move(city)},
m_suite {suite}
{
}
friend std::ostream& operator<<(std::ostream &out, const Address &address)
{
out << "Address: (street: " << address.m_street << ", city: " << address.m_city << ", suite: " << address.m_suite << ")\n";
return out;
}
Address(const Address &other) = delete;
Address& operator=(const Address &other) = delete;
Address(Address &&other) : m_street {std::move(other.m_street)},
m_city {std::move(other.m_city)},
m_suite {std::move(other.m_suite)}
{
}
};
class Contact {
const std::string m_name;
const Address m_address;
public:
Contact(const std::string &name, Address &address) : m_name {std::move(name)},
m_address {std::move(address)}
{
}
friend std::ostream& operator<<(std::ostream& out, const Contact &contact)
{
out << "Contact: " << contact.m_name << "\n" << contact.m_address << "\n";
return out;
}
};
int main()
{
Address address1 {"123 East Dr", "London", 123};
Contact john {"John Doe", address1};
std::cout << john;
std::cout << address1;
return 0;
}
我得到以下输出:
Contact: John Doe
Address: (street: 123 East Dr, city: London, suite: 123)
Address: (street: 123 East Dr, city: London, suite: 123)
为什么 address1 变量的内容没有移动?打印输出不应该是
Address: (street: , city: , suite: <whatever>)
另外,为什么对主要是代码的帖子有限制?一切都在代码中给出。我对移动语义很感兴趣,所以我创建了 address1 变量来保存一些地址。我使用相同的变量来初始化 Contact 类型的对象(使用移动语义),但没有执行移动语义,并且 address1 变量仍然保持相同的值。
【问题讨论】:
-
Why isn't the content of the address1 variable moved?为什么会这样?它不是右值。 -
但它作为一个引用传递给Contact构造函数,然后执行移动以从中取出一个右值?
-
最好有
Contact(const std::string &name, Address&& address)。
标签: c++ c++11 move-semantics