由参考引起的意外复制 - 构造:我做错了什么?

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.

Jam*_*lis 5

auto opc声明一个对象,而不是引用.就像你说过的那样OPC opc.

如果你想opc成为参考,你需要auto& opc.