繁体   English   中英

构造函数中的const_cast可接受

[英]const_cast in constructor acceptable

这是对const_cast的有效使用吗? 我在构造函数中使用它,它看起来如下:

KeyLiteObject(const char * extension, const char * swap_suffix)
        :    _extension(extension),
             _swap_suffix(swap_suffix),
             _swap_suffix_extension(swap_suffix) 
{
    const_cast<std::string*>(&_swap_suffix_extension)->append(_extension);
}

是的,字符串永远不会改变。

假设_swap_suffix_extension是const std :: string,那么为什么不这样做呢:

KeyLiteObject(const char * extension, const char * swap_suffix)
        :    _extension(extension),
             _swap_suffix(swap_suffix),
             _swap_suffix_extension( std::string( swap_suffix ) + std::string( extension ) ) 
{
}

然后,您可以完全避免const_cast ...

只要有可能,就避免使用const_cast ,并且在这里对于任何给定类型都是有可能的。 只需创建一个使用两个参数的助手函数,组成常量的最终值并在初始化程序中使用它:

// header file
struct test { 
   const type x; 
   test( type const & a, type const & b );
};
// implementation file
namespace {
   type compose( type const & arg1, type const & arg2 ) {
      // calculate the actual value here
   }
}
test::test(type const & a, type const & b) 
      : x( compose(a,b) ) 
{} 

这样做的代价只是在实现文件中编写了一个免费的( static或在未命名的名称空间中)函数,如果为函数选择了适当的名称,其结果将可读。 在您的情况下: concatenateconcat是不错的选择。

虽然在示例中使用const_cast不会导致未定义的行为,但出于个人原因,我会避免使用它。 强制转换使用C ++(与C或Java进行比较)很麻烦,原因是:这样它们将引起程序员的注意: 奇怪的事情在这里发生! 如果您开始撒石膏,那么您将习惯于看到它们,它们将变得自然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM