1

这是对 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);
}

是的,琴弦永远不会改变。

4

2 回答 2

7

假设 _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 ...

于 2011-01-21T09:41:58.520 回答
2

尽可能避免使用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在实现文件中编写一个免费的(或在未命名的命名空间中)函数,如果您为函数选择合适的名称,则结果是可读的。在您的情况下:concatenate或者concat将是不错的选择。

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

于 2011-01-21T10:58:58.247 回答