std::make_unique()(和类似的功能)有一点问题:
#include <cstdio>
#include <memory>
using namespace std;
struct S
{
S() { printf("ctor\n"); }
~S() { printf("dtor\n"); }
S(S const&) { printf("cctor\n"); }
S(S&&) { printf("mctor\n"); }
};
S foo() { return S(); }
int main()
{
{
printf("--------------- case 1 ---------------\n");
unique_ptr<S> s1 = make_unique<S>( foo() );
}
{
printf("--------------- case 2 ---------------\n");
unique_ptr<S> s2 { new S( foo() ) };
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
--------------- case 1 ---------------
ctor
mctor
dtor
dtor
--------------- case 2 …Run Code Online (Sandbox Code Playgroud)