Merge #10498: Use static_cast instead of C-style casts for non-fundamental types

9ad6746ccd Use static_cast instead of C-style casts for non-fundamental types (practicalswift)

Pull request description:

  A C-style cast is equivalent to try casting in the following order:

  1. `const_cast(...)`
  2. `static_cast(...)`
  3. `const_cast(static_cast(...))`
  4. `reinterpret_cast(...)`
  5. `const_cast(reinterpret_cast(...))`

  By using `static_cast<T>(...)` explicitly we avoid the possibility of an unintentional and dangerous `reinterpret_cast`. Furthermore `static_cast<T>(...)` allows for easier grepping of casts.

  For a more thorough discussion, see ["ES.49: If you must use a cast, use a named cast"](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es49-if-you-must-use-a-cast-use-a-named-cast) in the C++ Core Guidelines (Stroustrup & Sutter).

Tree-SHA512: bd6349b7ea157da93a47b8cf238932af5dff84731374ccfd69b9f732fabdad1f9b1cdfca67497040f14eaa85346391404f4c0495e22c467f26ca883cd2de4d3c
This commit is contained in:
MarcoFalke 2018-02-07 16:15:16 -05:00
commit 0277173b1d
No known key found for this signature in database
GPG key ID: D2EA4850E7528B25
24 changed files with 44 additions and 44 deletions

View file

@ -59,7 +59,7 @@ public:
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*(CAddress*)this);
READWRITE(*static_cast<CAddress*>(this));
READWRITE(source);
READWRITE(nLastSuccess);
READWRITE(nAttempts);

View file

@ -33,14 +33,14 @@ CScript ParseScript(const std::string& s)
if (op < OP_NOP && op != OP_RESERVED)
continue;
const char* name = GetOpName((opcodetype)op);
const char* name = GetOpName(static_cast<opcodetype>(op));
if (strcmp(name, "OP_UNKNOWN") == 0)
continue;
std::string strName(name);
mapOpNames[strName] = (opcodetype)op;
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = (opcodetype)op;
mapOpNames[strName] = static_cast<opcodetype>(op);
}
}

View file

@ -525,7 +525,7 @@ struct event_base* EventBase()
static void httpevent_callback_fn(evutil_socket_t, short, void* data)
{
// Static handler: simply call inner handler
HTTPEvent *self = ((HTTPEvent*)data);
HTTPEvent *self = static_cast<HTTPEvent*>(data);
self->handler();
if (self->deleteWhenTriggered)
delete self;

View file

@ -297,7 +297,7 @@ CNode* CConnman::FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if ((CNetAddr)pnode->addr == ip) {
if (static_cast<CNetAddr>(pnode->addr) == ip) {
return pnode;
}
}
@ -308,7 +308,7 @@ CNode* CConnman::FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (subNet.Match((CNetAddr)pnode->addr)) {
if (subNet.Match(static_cast<CNetAddr>(pnode->addr))) {
return pnode;
}
}
@ -330,7 +330,7 @@ CNode* CConnman::FindNode(const CService& addr)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if ((CService)pnode->addr == addr) {
if (static_cast<CService>(pnode->addr) == addr) {
return pnode;
}
}
@ -370,7 +370,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
return nullptr;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
CNode* pnode = FindNode(static_cast<CService>(addrConnect));
if (pnode)
{
LogPrintf("Failed to open new connection, already connected\n");
@ -398,7 +398,7 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
// Also store the name we used to connect in that CNode, so that future FindNode() calls to that
// name catch this early.
LOCK(cs_vNodes);
CNode* pnode = FindNode((CService)addrConnect);
CNode* pnode = FindNode(static_cast<CService>(addrConnect));
if (pnode)
{
pnode->MaybeSetAddrName(std::string(pszDest));
@ -559,7 +559,7 @@ void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t ba
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
if (subNet.Match(static_cast<CNetAddr>(pnode->addr)))
pnode->fDisconnect = true;
}
}
@ -1965,7 +1965,7 @@ void CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFai
}
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) ||
FindNode(static_cast<CNetAddr>(addrConnect)) || IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return;
} else if (FindNode(std::string(pszDest)))

View file

@ -2863,7 +2863,7 @@ static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman)
CNodeState &state = *State(pnode->GetId());
for (const CBlockReject& reject : state.rejects) {
connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, std::string(NetMsgType::BLOCK), reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
}
state.rejects.clear();

View file

@ -522,17 +522,17 @@ unsigned short CService::GetPort() const
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
return static_cast<CNetAddr>(a) != static_cast<CNetAddr>(b) || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const

View file

@ -572,7 +572,7 @@ bool HaveNameProxy() {
bool IsProxy(const CNetAddr &addr) {
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy))
return true;
}
return false;

View file

@ -86,14 +86,14 @@ public:
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
*(static_cast<CBlockHeader*>(this)) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*(CBlockHeader*)this);
READWRITE(*static_cast<CBlockHeader*>(this));
READWRITE(vtx);
}

View file

@ -346,8 +346,8 @@ public:
READWRITE(nTime);
uint64_t nServicesInt = nServices;
READWRITE(nServicesInt);
nServices = (ServiceFlags)nServicesInt;
READWRITE(*(CService*)this);
nServices = static_cast<ServiceFlags>(nServicesInt);
READWRITE(*static_cast<CService*>(this));
}
// TODO: make private (improves encapsulation)

View file

@ -705,7 +705,7 @@ int main(int argc, char *argv[])
if (BitcoinCore::baseInitialize()) {
app.requestInitialize();
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), (HWND)app.getMainWinId());
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), static_cast<HWND>(app.getMainWinId()));
#endif
app.exec();
app.requestShutdown();

View file

@ -599,7 +599,7 @@ void BitcoinGUI::createTrayIconMenu()
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow *)this);
dockIconHandler->setMainWindow(static_cast<QMainWindow*>(this));
trayIconMenu = dockIconHandler->dockMenu();
#endif
@ -922,13 +922,13 @@ void BitcoinGUI::message(const QString &title, const QString &message, unsigned
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
QMessageBox mBox(static_cast<QMessageBox::Icon>(nMBoxIcon), strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != nullptr)
*ret = r == QMessageBox::Ok;
}
else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
notificator->notify(static_cast<Notificator::Class>(nNotifyIcon), strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent *e)

View file

@ -142,7 +142,7 @@ CoinControlDialog::CoinControlDialog(const PlatformStyle *_platformStyle, QWidge
if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool())
ui->radioTreeMode->click();
if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder"))
sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt()));
sortView(settings.value("nCoinControlSortColumn").toInt(), (static_cast<Qt::SortOrder>(settings.value("nCoinControlSortOrder").toInt())));
}
CoinControlDialog::~CoinControlDialog()
@ -428,7 +428,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
if (amount > 0)
{
CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0));
CTxOut txout(amount, static_cast<CScript>(std::vector<unsigned char>(24, 0)));
txDummy.vout.push_back(txout);
fDust |= IsDust(txout, ::dustRelayFee);
}
@ -519,7 +519,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
// Never create dust outputs; if we would, just add the dust to the fee.
if (nChange > 0 && nChange < MIN_CHANGE)
{
CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0));
CTxOut txout(nChange, static_cast<CScript>(std::vector<unsigned char>(24, 0)));
if (IsDust(txout, ::dustRelayFee))
{
nPayFee += nChange;

View file

@ -24,7 +24,7 @@ void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event)
else if (event->key() == Qt::Key_Escape) // press esc -> close dialog
{
event->ignore();
CoinControlDialog *coinControlDialog = (CoinControlDialog*)this->parentWidget();
CoinControlDialog *coinControlDialog = static_cast<CoinControlDialog*>(this->parentWidget());
coinControlDialog->done(QDialog::Accepted);
}
else

View file

@ -351,7 +351,7 @@ void SendCoinsDialog::on_sendButton_clicked()
SendConfirmationDialog confirmationDialog(tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
if(retval != QMessageBox::Yes)
{

View file

@ -38,7 +38,7 @@ SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle)
float fontFactor = 1.0;
float devicePixelRatio = 1.0;
#if QT_VERSION > 0x050100
devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio();
devicePixelRatio = static_cast<QGuiApplication*>(QCoreApplication::instance())->devicePixelRatio();
#endif
// define text to place

View file

@ -322,7 +322,7 @@ void TransactionView::chooseWatchonly(int idx)
if(!transactionProxyModel)
return;
transactionProxyModel->setWatchOnlyFilter(
(TransactionFilterProxy::WatchOnlyFilter)watchOnlyWidget->itemData(idx).toInt());
static_cast<TransactionFilterProxy::WatchOnlyFilter>(watchOnlyWidget->itemData(idx).toInt()));
}
void TransactionView::changedSearch()

View file

@ -695,7 +695,7 @@ bool WalletModel::bumpFee(uint256 hash)
questionString.append("</td></tr></table>");
SendConfirmationDialog confirmationDialog(tr("Confirm fee bump"), questionString);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
QMessageBox::StandardButton retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result());
// cancel sign&broadcast if users doesn't want to bump the fee
if (retval != QMessageBox::Yes) {

View file

@ -56,7 +56,7 @@ bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pM
void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId)
{
typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
PSHUTDOWNBRCREATE shutdownBRCreate = static_cast<PSHUTDOWNBRCREATE>(GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"));
if (shutdownBRCreate == nullptr) {
qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
return;

View file

@ -568,7 +568,7 @@ public:
pc += nSize;
}
opcodeRet = (opcodetype)opcode;
opcodeRet = static_cast<opcodetype>(opcode);
return true;
}

View file

@ -226,7 +226,7 @@ BOOST_AUTO_TEST_CASE(versionbits_test)
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
const Consensus::Params &mainnetParams = chainParams->GetConsensus();
for (int i=0; i<(int) Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
uint32_t bitmask = VersionBitsMask(mainnetParams, (Consensus::DeploymentPos)i);
uint32_t bitmask = VersionBitsMask(mainnetParams, static_cast<Consensus::DeploymentPos>(i));
// Make sure that no deployment tries to set an invalid bit.
BOOST_CHECK_EQUAL(bitmask & ~(uint32_t)VERSIONBITS_TOP_MASK, bitmask);
@ -238,7 +238,7 @@ BOOST_AUTO_TEST_CASE(versionbits_test)
// activated soft fork could be later changed to be earlier to avoid
// overlap.)
for (int j=i+1; j<(int) Consensus::MAX_VERSION_BITS_DEPLOYMENTS; j++) {
if (VersionBitsMask(mainnetParams, (Consensus::DeploymentPos)j) == bitmask) {
if (VersionBitsMask(mainnetParams, static_cast<Consensus::DeploymentPos>(j)) == bitmask) {
BOOST_CHECK(mainnetParams.vDeployments[j].nStartTime > mainnetParams.vDeployments[i].nTimeout ||
mainnetParams.vDeployments[i].nStartTime > mainnetParams.vDeployments[j].nTimeout);
}

View file

@ -133,7 +133,7 @@ TorControlConnection::~TorControlConnection()
void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
struct evbuffer *input = bufferevent_get_input(bev);
size_t n_read_out = 0;
char *line;
@ -178,7 +178,7 @@ void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
if (what & BEV_EVENT_CONNECTED) {
LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
self->connected(*self);
@ -725,7 +725,7 @@ fs::path TorController::GetPrivateKeyFile()
void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
{
TorController *self = (TorController*)arg;
TorController *self = static_cast<TorController*>(arg);
self->Reconnect();
}

View file

@ -46,7 +46,7 @@ struct CDiskTxPos : public CDiskBlockPos
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*(CDiskBlockPos*)this);
READWRITE(*static_cast<CDiskBlockPos*>(this));
READWRITE(VARINT(nTxOffset));
}

View file

@ -1689,9 +1689,9 @@ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Para
int32_t nVersion = VERSIONBITS_TOP_BITS;
for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
ThresholdState state = VersionBitsState(pindexPrev, params, static_cast<Consensus::DeploymentPos>(i), versionbitscache);
if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
nVersion |= VersionBitsMask(params, static_cast<Consensus::DeploymentPos>(i));
}
}

View file

@ -408,7 +408,7 @@ public:
mapValue["timesmart"] = strprintf("%u", nTimeSmart);
}
READWRITE(*(CMerkleTx*)this);
READWRITE(*static_cast<CMerkleTx*>(this));
std::vector<CMerkleTx> vUnused; //!< Used to be vtxPrev
READWRITE(vUnused);
READWRITE(mapValue);