c++ - 如何在设置字符串值时优化函数调用?

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

<分区>

在下面的代码片段中,我从 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;
}

最佳答案

如果您的问题是在不同的行中使用不同的参数调用函数,您可以使用 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 。因此,请在适当的时候使用它们并避免手动分配内存。

关于c++ - 如何在设置字符串值时优化函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570689/

相关文章:

类中的 C++ typedef

c++ - 在命名空间范围之外定义命名空间的变量成员

c++ - 编译单个大头文件(VS : C1063)

c++ - LNK2001 未解析的外部符号与 CPP_XLOPER

c++ - 访问 CALLBACK 函数中的对象字段 (WINAPI - C++)

c++ - 继承自c++标准库List类,增加更多方法

c++ - 是否可以在 C++ 中为嵌入式平台创建新的原始类型?

c++ - 如何使输出函数将格式化输出写入屏幕和输出文件

python - 为什么python没有内置函数mean()?

javascript - 无法分配元素的最后位置坐标