【发布时间】:2019-04-12 22:40:54
【问题描述】:
我试图了解何时调用构造函数参数的移动构造函数。
我将使用下面实际项目中的一些示例和场景来更好地说明我的问题。
解释一下为什么我会看到这些场景的结果会非常有帮助!
//The following code is common to all examples
//This code is the place the object creation begins
std::unique_ptr<AI::Pathfinding::cDirectedWeightedGraph> graph = std::make_unique<AI::Pathfinding::cDirectedWeightedGraph>(std::move(connections));
x---------------------------------------------- --------------x
场景 1:
//Here is the actual constructor for the class
cDirectedWeightedGraph(std::vector<cConnection> i_connections) : m_connections(i_connections) {}
结果: 调用 std::vector 类的移动构造函数。
x---------------------------------------------- --------------x
场景 2:
//Here is the actual constructor for the class
cDirectedWeightedGraph(std::vector<cConnection>&& i_connections) : m_connections(i_connections) {}
结果: 未调用 std::vector 类的移动构造函数。
x---------------------------------------------- --------------x
场景 3:
//Here is the actual constructor for the class
cDirectedWeightedGraph(std::vector<cConnection>&& i_connections) : m_connections(std::move(i_connections)) {}
结果: 调用 std::vector 类的移动构造函数。
x---------------------------------------------- --------------x
场景 4:
//Here is the actual constructor for the class
cDirectedWeightedGraph(std::vector<cConnection> i_connections) : m_connections(std::move(i_connections)) {}
结果: 调用 std::vector 类的移动构造函数。
x---------------------------------------------- --------------x
观察/跟进问题:
参数是否被声明为右值引用似乎根本不重要。
除了为您的类编写移动构造函数或移动赋值运算符之外,您是否需要在构造函数中使用右值引用?
我假设在调用构造函数的位置,如果不传递右值引用,就无法调用移动构造函数(无论哪种方式,这似乎都是不好的做法,我只是好奇)。我正在使用 std::move() 生成右值引用。
【问题讨论】:
标签: c++11 optimization constructor move-constructor