模板类隐式复制构造函数问题
在 gdb 中单步执行我的程序,第 108 行立即返回到调用函数,并且不调用 A 类中的复制构造函数,就像(我认为)它应该的那样:
template <class S> class A{
//etc...
A( const A & old ){
//do stuff...
}
//etc...
};
template <class T> class B{
//etc...
A<T> ReturnsAnA(){
A<T> result;
// do some stuff with result
return result; //line 108
}
//etc...
};
有任何提示吗?我已经为这个问题苦苦思索了四个小时,但似乎无法弄清楚这里发生了什么。
Stepping through my program in gdb, line 108 returns right back to the calling function, and doesn't call the copy constructor in class A, like (I thought) it should:
template <class S> class A{
//etc...
A( const A & old ){
//do stuff...
}
//etc...
};
template <class T> class B{
//etc...
A<T> ReturnsAnA(){
A<T> result;
// do some stuff with result
return result; //line 108
}
//etc...
};
Any hints? I've banged my head against the wall about this for 4 hours now, and can't seem to come up with what's happening here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(指定)返回值优化已生效。作为优化,您的复制构造函数将被删除(这是标准允许的,尽管会导致不同的行为)。
另请参阅了解返回值优化和返回临时值 - C++。
(模板与此无关。)
(Named) return value optimization is in effect. Your copy constructor is being removed as an optimization (this is permitted by the standard although results in different behavior).
See also Understanding return value optimization and returning temporaries - C++.
(Templates have nothing to do with this.)