unique_ptr作为模板参数

unique_ptr as a template parameter

本文关键字:参数 ptr unique      更新时间:2023-10-16

为什么在VS 2017中编译?

#include <memory>
#include <iostream>
using namespace std;
struct x 
{
x()  { cout << "x()" << endl; }
~x() { cout << "~x()" << endl; }
};
template <typename T>
void foo(T&& item)
{
struct boo 
{
T item;
boo(T&& t)
: item(std::move(t))
{ }
};
new boo(std::move(item));
}
int main()
{
std::unique_ptr<x> b(new x);
foo(b); // I would expect that I should put std::move(b) here.
}

使用编写的代码,输出为

x()
~x()

如果foo(b)行写成foo(std::move(b)),则输出很简单

x()

x的实例被泄露。 我希望编写的代码是编译器错误,因为似乎unique_ptr<x>是在调用foo时复制

的?

当使用clang时,它不会编译:https://wandbox.org/permlink/HCIDXxS1yqyq7uCb 它适用于Visual Studio:http://rextester.com/GUR47187

所以它看起来像 VS 中的一个错误。

它始终适用于move:https://wandbox.org/permlink/u3N06Idr8ELo9SIp

此外,对于模板,应使用std::forward代替std::move

下面是查找 VS 如何解析模板的代码:

void __cdecl foo<classstd::unique_ptr<struct x,struct std::default_delete<struct x> >&>(class std::unique_ptr<struct x,struct std::default_delete<struct x> > &)

所以unique_ptr不是通过引用传递unique_ptr而移动的。