2

OPCへの参照を作成しているだけなのに、のコピーコンストラクターが呼び出されている複雑なテンプレートコードがありますOPC(実際のインスタンスはOP_S、の子クラスとしてOPC、コピーコンストラクターの呼び出しにはならないはずです)。

gcc4.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;
}

以下のJamesMcNellisが指摘したように答えauto&てください-の代わりに必要ですauto

4

2 に答える 2

5

auto opc参照ではなく、オブジェクトを宣言します。それはあなたが言ったのと同じですOPC opc

参照になりたい場合はopc、が必要auto& opcです。

于 2011-10-25T06:14:16.350 に答える
4

opc本来あるべきよりも参考にしたいのなら、

auto &opc = tf.getOPC();

C ++ 11では、autoauto &(幸いなことに)異なる意味があります。したがってgetOPC()、参照を返すかどうかに関係なくauto opc、オブジェクトが作成されます。

于 2011-10-25T06:14:02.483 に答える