相关疑难解决方法(0)

对于使用聚合初始化的结构,避免在make_unique/make_shared/emplace/etc中进行额外移动

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)

c++ c++11 c++14 c++17

14
推荐指数
1
解决办法
498
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

c++17 ×1