make_unique 完美转发

2023-02-12C/C++开发问题
1

本文介绍了make_unique 完美转发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为什么标准 C++11 库中没有 std::make_unique 函数模板?我发现

Why is there no std::make_unique function template in the standard C++11 library? I find

std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));

有点啰嗦.下面的不是更好吗?

a bit verbose. Wouldn't the following be much nicer?

auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);

这很好地隐藏了 new 并且只提到了一次类型.

This hides the new nicely and only mentions the type once.

无论如何,这是我对 make_unique 实现的尝试:

Anyway, here is my attempt at an implementation of make_unique:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

我花了很长时间才编译std::forward 的东西,但我不确定它是否正确.是吗?std::forward(args)... 到底是什么意思?编译器对此有何看法?

It took me quite a while to get the std::forward stuff to compile, but I'm not sure if it's correct. Is it? What exactly does std::forward<Args>(args)... mean? What does the compiler make of that?

推荐答案

C++ 标准化委员会主席 Herb Sutter 在他的 博客上写道:

Herb Sutter, chair of the C++ standardization committee, writes on his blog:

C++11 不包含 make_unique 部分是一个疏忽,而且几乎肯定会在未来添加.

That C++11 doesn’t include make_unique is partly an oversight, and it will almost certainly be added in the future.

他还给出了一个与 OP 给出的实现相同的实现.

He also gives an implementation that is identical with the one given by the OP.

std::make_unique 现在是 C++14.

这篇关于make_unique 完美转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6