简体   繁体   English

unique_ptr作为模板参数

[英]unique_ptr as a template parameter

Why does this compile in VS 2017? 为什么这会在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.
}

With the code as written, the output is 使用编写的代码,输出是

x()
~x()

If the foo(b) line were written as foo(std::move(b)) , then the output is simply 如果foo(b)行被写为foo(std::move(b)) ,那么输出就是简单的

x()

ie the instance of x is leaked. x的实例被泄露。 I would expect the code as written to be a compiler error, since it seems like the unique_ptr<x> is copied at the call to foo ? 我希望编写的代码是一个编译器错误,因为似乎在调用foo复制了unique_ptr<x>

When clang is used it doesn't compile: https://wandbox.org/permlink/HCIDXxS1yqyq7uCb And it works with Visual Studio: http://rextester.com/GUR47187 当使用clang时,它无法编译: https//wandbox.org/permlink/HCIDXxS1yqyq7uCb它适用于Visual Studio: http//rextester.com/GUR47187

So it looks like a bug in VS. 所以它看起来像VS中的一个错误。

It always works with move : https://wandbox.org/permlink/u3N06Idr8ELo9SIp 它始终适用于movehttps//wandbox.org/permlink/u3N06Idr8ELo9SIp

Also in case of templates std::forward should be used instead std::move . 同样在模板的情况下, 应使用 std::forward代替std::move

Here is code which finds how VS resolves templates: 以下是查找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> > &)

So unique_ptr is not moved just passed by reference to unique_ptr . 所以unique_ptr不动只是通过引用传递到unique_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM