为什么在Visual Studio C ++中无法编译?我正在使用Visual Studio 2017 15.7.1。它在clang和g ++中编译:
#include <utility>
#include <vector>
struct Foo {
Foo(int x) {}
Foo(Foo const& b) {}
};
struct Bar {
template <class... Args>
Bar(Args&&... args)
: foo(std::forward<Args>(args)...) {}
Foo foo;
};
void test() {
std::vector<Bar> v;
v.emplace_back(123);
}
错误是 error C2664: 'Foo::Foo(const Foo &)': cannot convert argument 1 from 'Bar' to 'int'
参见https://godbolt.org/g/bKb34v
编辑:我已经在这里提交此问题:https : //developercommunity.visualstudio.com/content/problem/252470/perfect-forwarding-compiler-bug.html
这是您的错误,而不是MSVC。
Foo
的copy构造函数不是noexcept
,并且没有move构造函数。Bar
的隐式声明的move构造函数也不noexcept
是,因为它需要为Foo
数据成员调用前面提到的copy构造函数。emplace_back
可以重新分配,并且由于Bar
看上去是可复制的,所以重新分配将复制现有元素,以保留强大的异常安全保证。const
或非const
Bar
左值进行复制。Bar
左值进行的复制。解决方法是限制构造函数模板,以使其不会被劫持。例如:
template <class... Args,
class = std::enable_if_t<std::is_constructible_v<Foo, Args...>>>
Bar(Args&&... args)
: foo(std::forward<Args>(args)...) {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句