我有一些复杂的模板代码,其中调用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;
}回答,正如James McNellis在下面所指出的-需要auto&而不是auto。
发布于 2011-10-25 06:14:16
auto opc声明一个对象,而不是引用。就像你说过OPC opc一样。
如果希望opc成为引用,则需要auto& opc。
发布于 2011-10-25 06:14:02
如果您想让opc作为参考,
auto &opc = tf.getOPC();在C++11中,auto和auto & (幸运地)有着不同的含义。因此,不管getOPC()返回一个引用,auto opc都会创建一个对象。
https://stackoverflow.com/questions/7885104
复制相似问题