从这个问题的先前版本开始,感谢@Gene,我现在能够使用一个更简单的示例重现此行为。
#include <iostream>
#include <vector>
class Wrapper
{
std::vector<int> const& bc;
public:
Wrapper(std::vector<int> const& bc) : bc(bc) { }
int GetSize() const { return bc.size(); }
};
class Adapter
{
Wrapper wrapper;
public:
Adapter(Wrapper&& w) : wrapper(w) { }
int GetSize() const { return wrapper.GetSize(); }
};
template <class T>
class Mixin : public Adapter
{
public:
//< Replace "Types ... args" with "Types& ... args" and it works even with Apple LLVM
template <class ... Types>
Mixin(Types ... args) : Adapter(T(args...)) { }
};
int main()
{
std::vector<int> data;
data.push_back(5);
data.push_back(42);
Mixin<std::vector<int>> mixin(data);
std::cout << "data: " << data.size() << "\n";
std::cout << "mixin: " << mixin.GetSize() << "\n";
return 0;
}
使用 Apple LLVM 的结果,使用 -std=c++11
和 -std=c++14
测试:
data: 2
mixin: -597183193
有趣的是,我也测试了这段代码@ideone它使用启用了 C++14 的 gcc-5.1,并且按预期工作!
data: 2
mixin: 2
为什么 mixin.GetSize()
在 Clang 上返回垃圾值,为什么它可以与 GCC-5.1 一起工作?
@Gene 建议我使用 Types ... args
创建 vector 的临时拷贝(并使用 Types& ... args
使其与LLVM),但该拷贝将包含相同的元素(因此也具有相同的大小)。
最佳答案
您有一个悬空引用,并且 mixin.GetSize()
正在产生 undefined behavior :
Mixin
内部的构造函数,T
=std::vector<int>
, 所以Adapter(T(args...))
正在路过Adapter
的构造函数是临时的std::vector<int>
-
Adapter
的构造函数参数是Wrapper&&
, 但我们传递给它一个std::vector<int>&&
, 所以我们调用Wrapper
的隐式转换构造函数 -
Wrapper
的构造函数参数是std::vector<int> const&
,我们将它传递给一个std::vector<int>&&
;右值被允许绑定(bind)到 const-lvalue 引用,所以这在语法上很好并且编译很好,但实际上我们绑定(bind)了Wrapper::bc
临时 - 构建完成后,在
Mixin
中创建的临时对象的生命周期的构造函数结束,Wrapper::bc
成为悬空引用;调用Adapter::GetSize
现在产出 UB
当 Mixin
的构造函数参数从 Types...
更改为至 Types&...
, Adapter(T(args...))
仍然通过Adapter
的构造函数是临时的 std::vector<int>
;它只是似乎起作用,因为您看到了 UB 的不同表现形式(可能堆栈看起来有点不同,因为正在制作的 std::vector<int>
拷贝较少)。即,代码的两个版本都同样损坏/错误!
所以,具体地回答这个问题:
Why does
mixin.GetSize()
return a garbage value on Clang and why does it work with GCC-5.1?
因为未定义行为的行为是未定义的。 ;-] 看起来可以工作是一种可能的结果,但代码仍然是错误的,正确的外表纯粹是表面的。
关于c++11 参数包错误行为与 Apple LLVM 7.0.0 但适用于 GCC-5.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34832169/