kfm*_*e04 2 c++ reference copy-constructor auto c++11
我有一些复杂的模板代码,其中复制构造函数OPC
被调用,即使我只是创建一个引用OPC
(实际的实例是OP_S
,作为子类OPC
,不应该导致复制构造调用).
我正在使用gcc 4.6.1
代码如下.
#include <stdio.h>
class OPC
{
public:
OPC() { }
OPC( const OPC& f ) {
fprintf( stderr, "CC called!!!\n" );
}
};
template<class T>
class SL : public T
{ };
template<class T>
class S : public SL<T>
{ };
class OP_S : public S<OPC>
{ };
class TaskFoo
{
public:
TaskFoo( OPC& tf ) :
m_opc( tf ),
m_copc( tf )
{ }
OPC& getOPC() { return m_opc; }
private:
OPC& m_opc;
const OPC& m_copc;
};
int main(int argc, char** argv)
{
OP_S op_s;
TaskFoo tf( op_s );
auto opc = tf.getOPC(); // this line results in a call to OPC's CC
return 0;
}
Run Code Online (Sandbox Code Playgroud)
詹姆斯麦克纳利斯在下面提到的答案 - 需要auto&
而不是auto
.