尚未调用移动构造函数
Move constructor hasn't been called
代码如下:
#include <memory>
#include <iostream>
template<typename T>
class Foo
{
public:
Foo(T&& val) :
val(std::make_unique<T>(
std::forward<T>(val)))
{
}
Foo(Foo&& that) :
val(std::move(that.val))
{
std::cout << *val << std::endl;
}
std::unique_ptr<int> val;
};
template<typename T>
void Func(Foo<T>&& val)
{
std::cout << *val.val << std::endl;
}
int main()
{
Foo<int> instance(10);
Func(std::move(instance));
return 0;
}
问题是我希望这里有两行输出(来自我的自定义移动构造函数和 'Func' 函数),但我只得到一行。为什么?
您的 Foo<int>
对象根本没有移动。 std::move
不动它;它仅使其可用于移动(通过将其转换为 xvalue)。但是,由于 Func
通过引用获取其参数,因此在调用它时不会构造 Foo<int>
对象,因此不会调用移动构造函数。
代码如下:
#include <memory>
#include <iostream>
template<typename T>
class Foo
{
public:
Foo(T&& val) :
val(std::make_unique<T>(
std::forward<T>(val)))
{
}
Foo(Foo&& that) :
val(std::move(that.val))
{
std::cout << *val << std::endl;
}
std::unique_ptr<int> val;
};
template<typename T>
void Func(Foo<T>&& val)
{
std::cout << *val.val << std::endl;
}
int main()
{
Foo<int> instance(10);
Func(std::move(instance));
return 0;
}
问题是我希望这里有两行输出(来自我的自定义移动构造函数和 'Func' 函数),但我只得到一行。为什么?
您的 Foo<int>
对象根本没有移动。 std::move
不动它;它仅使其可用于移动(通过将其转换为 xvalue)。但是,由于 Func
通过引用获取其参数,因此在调用它时不会构造 Foo<int>
对象,因此不会调用移动构造函数。