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
代替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
而移动的。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr
- 视觉 C++编译器在计算其参数之前是否允许将函数 ptr 存储在寄存器中?
- 如何调用传递的函数(函数 ptr 作为参数传递给函数)
- 为什么非常量ptr不能隐式地将ptr转换为常量作为模板中的参数
- 二进制泛型lambda不匹配ptr-to-function参数
- 分配const char *ptr数组参数?c++
- 函数PTR转换为带模板参数的函数
- ptr到成员模板参数的友元语法
- 将字符串引用作为参数传递时Ptr错误