【问题标题】:How can I optimize function calls while setting the string values? [closed]如何在设置字符串值时优化函数调用? [关闭]
【发布时间】:2019-08-20 09:34:26
【问题描述】:

在下面的代码 sn-p 中,我从 ReadFile() 函数调用 SetParams()Execute() 多次。 我可以通过单个调用优化每个 SetParams()Execute() 吗?

bool SubscriptionRead::ReadFile()
{
    IVerification* pReader = new FileReader();
    std::wstring oemPathPublicKey(oemFolderPath)
        , oemPathSessionKey(oemFolderPath)
        , oemPathUserChoices(oemFolderPath);
    oemPathPublicKey.append(PUBLIC_KEY_FILE);
    oemPathSessionKey.append(SESSION_KEY_FILE);
    oemPathUserChoices.append(USERCHOICES_FILE);
    pReader->SetParams((wchar_t*)oemPathPublicKey.c_str(), L"file");
    pReader->Execute();
    pReader->SetParams((wchar_t*)oemPathSessionKey.c_str(), L"file");
    pReader->Execute();
    pReader->SetParams((wchar_t*)oemPathUserChoices.c_str(), L"file");
    pReader->Execute();
    return True;
}

void FileReader::SetParams(wchar_t* wszParams, wchar_t* wszParamType)
{
    m_wszParamType = wszParamType;
    m_wszParams = wszParams;
}

bool FileReader::Execute()
{
    if (wcscmp(m_wszParamType, L"registry") == 0)
    {
        function1();
    }
    else
    {
        function2();
    }
    return true;
}

【问题讨论】:

  • 也许可以解释为什么你认为你不能,因为不清楚是什么问题
  • 是什么阻碍了您创建另一个在单个调用中执行此操作的函数?
  • 将需要的参数直接传递给Execute(),而不是使用其他函数来设置它们。如果您想将多个 Execute() 调用合并为一个,请更改参数,使其接受多对参数,或接受数组参数。还可以考虑使用标准库类型(如std::wstring,或者,如果传递一组,std::vector<std::wstring>)而不是使用wchar_t 的数组。
  • 老实说,我认为这很好。如果您还有更多要添加的内容,请担心。

标签: c++ function class c++11 optimization


【解决方案1】:

如果您的问题是在不同的行中调用具有不同参数的函数,您可以使用std::ref 如下迭代引用包装器的initializer_list 到对象(即std::wstring s ),这减少了一些打字:

#include <functional>        // std::ref
#include <initializer_list>  // std::initializer_list

bool SubscriptionRead::ReadFile()
{
    IVerification* pReader = new FileReader();  
    // .... other code
    for(auto strKey: {std::ref(oemPathPublicKey), std::ref(oemPathSessionKey), std::ref(oemPathSessionKey)})
    {
        pReader->SetParams((wchar_t*)strKey.c_str(), L"file");
        pReader->Execute(); // does it needed to executed for every path? if no: outside the loop!
    }
    return True;
}

还要注意,在现代 C++ 中,您有 smart pointers。因此,请在适当的时候使用它们,并避免手动分配内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2014-02-16
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多