我有一个包含用 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/