有效地 const_cast-ing 常量引用参数
我有一个成员函数,它接受另一个对象的常量引用参数。我想 const_cast 这个参数以便在成员函数中轻松使用它。为此,以下哪个代码更好?:
void AClass::AMember(const BClass & _BObject)
{
// FORM #1 - Cast as an object:
BClass BObject = const_cast<BClass &>(_BObject);
// ...
}
void AClass::AMember(const BClass & _BObject)
{
// FORM #2 - Cast as a reference:
BClass & BObject = const_cast<BClass &>(_BObject);
// ...
}
您能比较一下这两种形式吗?在速度和内存使用方面哪一个更好?
I have a member function which takes a constant reference parameter to another object. I want to const_cast this parameter in order to easily use it inside the member function. For this purpose, which of the following codes is better?:
void AClass::AMember(const BClass & _BObject)
{
// FORM #1 - Cast as an object:
BClass BObject = const_cast<BClass &>(_BObject);
// ...
}
void AClass::AMember(const BClass & _BObject)
{
// FORM #2 - Cast as a reference:
BClass & BObject = const_cast<BClass &>(_BObject);
// ...
}
Can you please compare these two forms? Which one is better in criteria of speed and memory usage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个没有任何意义,因为您放弃了
_BObject
的常量,只是稍后将其作为常量引用传递给BClass
构造函数并创建一个副本,B对象
。第二个实现了它的意思——抛弃常量并保留对原始对象的引用。所以如果你问我,第二个更好。但请注意,const_cast
并不总是安全的。The first one doesn't make any sense as you cast away constness of
_BObject
to only later pass it as a constant reference toBClass
constructor and create a copy,BObject
. The second one does what it means - casts away the constness and keeps the reference to the original object. So if you ask me, the second one is better. Be aware though thatconst_cast
is not always safe.第一个版本制作对象的副本。第二个版本没有。所以第二个版本会更快,除非你想复制。
顺便说一句,所有以下划线开头后跟大写字母的标识符都保留供编译器使用。您不应该使用像
_BObject
这样的变量名称。The first version makes a copy of the object. The second version doesn't. So the second version will be faster unless you want to make a copy.
By the way, all identifiers that start with an underscore followed by a capital letter are reserved for use by the compiler. You should not be using variable names like
_BObject
.