【发布时间】:2018-09-19 23:40:43
【问题描述】:
我有一个类,它包含一个在构造过程中移动对象的构造函数:
class SomeClass
{
private:
const std::unique_ptr<Base> foo;
public:
template <typename T>
inline explicit SomeClass(T&& derived) noexcept
: foo(std::make_unique<T>(derived))
{
static_assert(std::is_base_of<Base, T>::value);
}
};
当我只需要一个实例时,可以毫无问题地构造类的对象:
class Derived : public Base
{
// ...
};
Derived bar(...);
SomeClass baz(std::move(bar));
// Or
SomeClass baz(Derived(...));
但是我无法将 SomeClass 类型的任何对象放置(或推送)到std::vector<SomeClass>。
std::vector<SomeClass> vec;
Derived bar(...);
vec.emplace_back(std::move(bar)); // Does not work.
vec.emplace_back(Derived(...)); // Does not work.
请你解释一下为什么不能放置物体?我认为emplace_back 使用的完美转发将允许就地构造SomeClass 的实例,就像构造单个实例一样。
您能否还解释一下如何修改内容以允许构造std::vector<SomeClass>?
我的猜测是,由于构造函数参数是通过 move 传递的,因此它们不会一直转发到 emplace_back 方法中的构造函数。
【问题讨论】:
-
这不是移动构造函数,也绝不是
noexcept。 -
SomeClass有默认构造函数。 -
它不是移动构造函数,因为它不会通过移动另一个预先存在的实例来构造新实例,但它会在构造函数期间移动给定的参数。我没有看到任何关于 noexcept 的警告。
-
所以现在重新查看它,我发现您将
Detector重命名为SomeClass但忘记在看起来像成员函数的构造函数的名称上执行此操作。但是,它仍然需要一个 forwarding 引用,它不是移动构造函数。 -
谢谢,我已编辑以修正错字并澄清我所说的“仅移动构造函数”的意思。
标签: c++ move stdvector unique-ptr emplace