相关疑难解决方法(0)

在定位C++ 03时使用std :: basic_string <t>作为连续缓冲区是否合理?

我知道在C++ 03中,从技术上讲,std::basic_string模板不需要具有连续的内存.但是,我很好奇有多少实现存在于实际利用这种自由的现代编译器.例如,如果想要用来basic_string接收某些C API的结果(如下面的例子),分配一个向量只是为了立即将它变成一个字符串似乎很愚蠢.

例:

DWORD valueLength = 0;
DWORD type;
LONG errorCheck = RegQueryValueExW(
        hWin32,
        value.c_str(),
        NULL,
        &type,
        NULL,
        &valueLength);

if (errorCheck != ERROR_SUCCESS)
    WindowsApiException::Throw(errorCheck);
else if (valueLength == 0)
    return std::wstring();

std::wstring buffer;
do
{
    buffer.resize(valueLength/sizeof(wchar_t));
    errorCheck = RegQueryValueExW(
            hWin32,
            value.c_str(),
            NULL,
            &type,
            &buffer[0],
            &valueLength);
} while (errorCheck == ERROR_MORE_DATA);

if (errorCheck != ERROR_SUCCESS)
    WindowsApiException::Throw(errorCheck);

return buffer;
Run Code Online (Sandbox Code Playgroud)

我知道像这样的代码可能会略微降低可移植性,因为它意味着它std::wstring是连续的 - 但我想知道这个代码是多么不可移植.换句话说,编译器如何实际利用具有非连续内存的自由?


编辑:我更新了这个问题,提到C++ 03.读者应注意,在定位C++ 11时,标准现在要求basic_string是连续的,因此在定位该标准时,上述问题不是问题.

c++ string winapi stl c++03

32
推荐指数
2
解决办法
3480
查看次数

如何使用std :: find/std :: find_if与自定义类对象的向量?

我有一个代表一个被调用的用户的类Nick,我想std::find_if在其上使用,我想要查找用户列表向量是否包含我传入的相同用户名的对象.我尝试创建一个新Nick对象尝试了几次我要测试和重载的用户名== operator,然后尝试find/find_if在对象上使用:

    std::vector<Nick> userlist;
    std::string username = "Nicholas";

if (std::find(userlist.begin(), userlist.end(), new Nick(username, false)) != userlist.end())) {
    std::cout << "found";
}
Run Code Online (Sandbox Code Playgroud)

我已经超载了== operator所以比较Nick == Nick2应该工作,但函数返回error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Nick' (or there is no acceptable conversion).

这是我的Nick课程供参考:

class Nick {
private:
    Nick() {
        username = interest = email = "";
                    is_op = false;
    };
public:
    std::string …
Run Code Online (Sandbox Code Playgroud)

c++ stl stl-algorithm

26
推荐指数
3
解决办法
5万
查看次数

为什么编译器不执行类型转换?

请考虑以下代码.

#include <iostream>
#include <string>

struct SimpleStruct
{
    operator std::string () { return value; }
    std::string value;
};

int main ()
{
    std::string s;    // An empty string.
    SimpleStruct x;   // x.value constructed as an empty string.

    bool less = s < x; // Error here.
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码不能在g ++或Microsoft Visual C++上编译.编译器给出的错误报告是no match for operator '<' in 's < x'.问题是为什么编译器不是简单SimpleStruct xstring根据给定转换为operator string ()然后使用operator < ( string, string )

c++ operators type-conversion

10
推荐指数
1
解决办法
334
查看次数

标签 统计

c++ ×3

stl ×2

c++03 ×1

operators ×1

stl-algorithm ×1

string ×1

type-conversion ×1

winapi ×1