c++ - 设置类成员 unique_ptr<T[]> 数组而不复制

标签 c++ move-semantics unique-ptr initializer-list rvalue

我有一个包含用 unique_ptr 管理的 c 风格数组的类。我想提供一个构造函数:

class A {
  unique_ptr<T[]> p;
public:
  A(int d, X x) : p(new T[d]) {
    //Transfer from x to p without copying
  }
}

这样我就可以用类似的东西构建我的对象:

int main(..) {
  A a{n,{expr1,expr2,..}};
}

其中 {expr1,expr2,..} 包含初始化的值(在运行时计算)。由于这个列表是临时的,在我看来构建它是浪费资源,将它的值复制到实际对象中并丢弃它。

我相信 move 语义、右值和 C++11 的所有优秀特性应该有一个解决这个简单任务的方法,但我找不到它(我是 C++ 的新手)。

我想坚持使用 C 风格的数组,而不是转向 std::vectors。有解决办法吗?

最佳答案

是的,你可以使用完美转发:

#include <memory>
#include <string>

struct S
{
    S(int) {}
    S(S const&) = delete;
    S(S&&) = default;
};

template<typename T>
struct A
{
    std::unique_ptr<T[]> p;

    template<typename... Args>
    A(int d, Args&&... args)
        : p(new T[sizeof...(args)]{std::forward<Args>(args)...})
    {
    }
};

int main()
{
    A<int> a(0, 1, 2, 3, 4);

    A<std::string> b(0, "hello", "world!", "\n");

    S s(0);
    A<S> c(0, std::move(s), 2, 3);
}

关于c++ - 设置类成员 unique_ptr<T[]> 数组而不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44189649/

相关文章:

c++ - 在 C++ 中解析 "arguments"

c# - 浮点精度

c++ - 详细 move 语义

c++ - g++4.4 : iostream move semantics

C++ 11 智能指针的使用

c++ - std::unordered_set 中的非常量 find()

c++ - 按值传递/引用定义的实现或行为是否明智?

c++ - 返回到转换构造函数中的仅 move 类型

c++ - 为什么我不能使用迭代器将 unique_ptr 从集合 move 到函数参数?

c++ - 如何修复具有 unique_ptr 的对象的 vector