unique_ptr 作为模板参数
unique_ptr as a template parameter
为什么要在 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
should be used 而不是 std::move
.
Here is code 找出 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
。
为什么要在 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
should be used 而不是 std::move
.
Here is code 找出 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
。