根据Scott Meyers的说法,为了防止在const版本的getter和非const版本的getter中重复代码,请从非const版本调用该方法的const版本:static_cast<const A&>(*this).Methodology(); 但是,由于过度热心而意外使用我输入的Visual Assist X Intellisense:const_cast<const A&>(*this).Methodology();它运行得很好.
在这种情况下使用特定演员阵容有什么区别?
正在使用的IDE:Visual Studio 2010.
all:这是来自Effective C++ 3rd editiion
const_cast通常用于抛弃对象的常量.它是唯一能够做到这一点的C++风格的演员.
我的问题是const_cast可以将constness添加到非const对象吗?实际上我写了一个小程序试图批准我的想法.
class ConstTest
{
public:
void test() {
printf("calling non-const version test const function \n");
}
void test() const{
printf("calling const version test const function \n");
}
};
int main(int argc,char* argv){
ConstTest ct;
const ConstTest cct;
cct.test();
const_cast<const ConstTest&>(ct).test();//it is wrong to write this statement without the '&',why
}
Run Code Online (Sandbox Code Playgroud)
省略'&'会导致以下错误:
错误C2440:'const_cast':无法从'ConstTest'转换为'const ConstTest'
它表明const_cast可以添加constness,但似乎你必须强制转换为对象引用,这个引用的魔力是什么?
给定这两个修改并返回字符串的函数:
// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
// ...do something here to modify the string...
return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
std::string s( str );
return modify( s ); // could this not call the "const" version again?
}
Run Code Online (Sandbox Code Playgroud)
这段代码适用于我使用GCC g ++,但我不明白为什么/如何.我担心第二个函数会调用自己,让我失控,直到堆栈耗尽为止.这保证有效吗?
我正在将文件映射到内存并将 a 返回const char*到第一个字节:
Mapper(const char* path, const char*& firstByte, size_t& fileSize);
Run Code Online (Sandbox Code Playgroud)
但是外部代码(我无法更改它)我正在使用它char*(尽管它不会更改缓冲区):
void externalCode(char* bytes);
Run Code Online (Sandbox Code Playgroud)
所以我收到一个编译器错误(将 const 传递给非常量)并且不得不将我的 const 数组复制到一个非常量数组。
文件很大,所以我不想复制它们。这里最好的解决方案是什么?重载我的映射器以返回非常量?常量?
c++ ×4
casting ×1
const-cast ×1
function ×1
recursion ×1
reference ×1
signature ×1
static-cast ×1