简体   繁体   中英

C++ function returning const char *

I've developed a small helper function for a unit test class, which takes my vector<unsigned char> and converts it back to a const char * . I wrote this so I can pass it to gtest's ASSERT_STREQ macro for simple comparisons. Here it is:

const char * convertVecToChar(std::vector<unsigned char>& source)
{
    std::vector<unsigned char>::size_type size = source.size();
    char* data = (char*)malloc(sizeof(char) * (size + 1)); 
    memcpy(data, &source[0], size);
    data[size] = 0;
    return data;
}

And here's an example of it being called:

ASSERT_STREQ("de", convertVecToChar(somevector));

I presume this is leaky however as I'm calling malloc , but without calling delete further down the road?

Is there a more elegant way to do this, which does not involve creating a separate const char * variable for every time I call ASSERT_STREQ within a test method?

Big thanks in advance for all responses.

Chris

Return a std::string instead of a char* ( malloc() , or new , unrequired):

std::string convertVecToChar(std::vector<unsigned char>& source)
{
    return std::string(source.begin(), source.end());
}

and use:

ASSERT_STREQ("de", convertVecToChar(somevector).c_str());  

Overload operator== , then you can just use ASSERT_EQ:

bool operator==(const char* nullTerminatedChars,
                const std::vector<char>& vecChars)
{
    return std::string(nullTerminatedChars) ==
           std::string(vecChars.begin(), vecChars.end());
}

Use as:

std::vector<char> chars;
ASSERT_EQ("de", chars);

You'll need to overload operator<<(std::ostream& ... too, as GoogleTest uses it to convert arguments to the assert into error messages if the assertion fails.

edit:

std::ostream& operator<<(std::ostream& os, const std::vector<char>& chars)
{
    return os << std::string(chars.begin(), chars.end());
}

You should just use string container - no need to worry about memory leaks.

BTW - As you are using C++ - just stick to new and delete .

source.push_back(0);
ASSERT_STREQ("de", (char*)&source[0]);
source.pop_back();

I was going to recommend using std::string too , but I was wondering, why not just compare the contents of the vector? You can access the raw data through &source[0] , so you could do:

ASSERT_STREQ("de", (char*)&source[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM