首先,我已经读过这个问题:有没有办法可以检测到使用宏包含标准头文件?
我想知道的是:#ifdef用于检测是否包含c ++标准头的任务有多安全,如下面的代码所示:
namespace overwrite
{
using byte = unsigned char;
template <bool safeMode = true, typename generic>
void withZeros( generic *toBeOverwriten, size_t length = 1 )
{
// do stuff
}
#ifdef _GLIBCXX_RANDOM // found this macro inside <random>
template <bool safeMode = true, typename generic>
void withRandomData( generic *toBeOverwriten, byte min = 0, byte max = 255 )
{
// do stuff expecting <random> to be included
}
#endif
}
Run Code Online (Sandbox Code Playgroud)
...所以我不能只是将一些std函数重载为上面提到的问题的答案中提出的"更糟糕的匹配",而且还编译或不编译我的头文件的整个函数/部分,这取决于包含一些std头.
我怀疑这种方式根本不安全吗?如果是这样,有没有其他方法来检测这个,以便做我想做的事情?
关于"为什么我不只是包括标题"......
我给出的代码作为我正在尝试做的一个例子就是一个例子.我脑子里也有其他的东西,只是想知道是否有另一种方法来检查包含标题而不检查你希望在那些内部定义的宏.然后我想起了这个真实的情况,我问自己这个问题,我开始问我在问什么......因为,在这个特定情况下,我不想包含很多代码(<random> …
我正在尝试编写一个可以读入文本文件的程序,并将其中的每个单词存储为字符串类型向量中的条目.我确信我这样做是非常错误的,但是自从我试图做到这一点以来,我已经忘记了它是如何完成的.任何帮助是极大的赞赏.提前致谢.
码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我有这个函数用于零覆盖的东西,它使用static_assert检查给定的东西的类型是否是POD类型:
template <bool safeMode = true, typename generic>
void overwriteWithZeros( generic *variableAddress )
{
if (safeMode) static_assert(std::is_pod<generic>::value, "Only POD types can be properly overwriten");
const size_t size = sizeof(generic);
unsigned char *variableData = (unsigned char*)(variableAddress);
for (size_t i = 0; i < size; i++)
variableData[i] = 0;
}
Run Code Online (Sandbox Code Playgroud)
我在这里打电话:
int main()
{
being *creature = new being(100, "a guinea pig"); // being is not a POD type
overwriteWithZeros<false>(creature);
// totally unrelated stuff...
}
Run Code Online (Sandbox Code Playgroud)
因为它safeMode是一个编译时的值,我不知道为什么它会发生它是真的或者它是假的,static_assert总是"发生",给我当时预期的错误,因为being它不是POD类型,就像if在static_assert之前一样根本不在那里. …
在节省时间和减少操作数量方面,(*this)在this->经常使用of的成员函数的开头创建对它的引用有用吗?编译器(gcc最让我感兴趣)已经为我优化了吗?有没有理由不这样做?
例:
void A::checkBytes( const byte * dataChunk, uint32_t chunkSize )
{
A & self = (*this);
bool UTF8Valid = self.InvalidSequences & 1;
byte current, expectedUTF8Bytes = 0;
for (uint32_t i = 0; i < chunkSize; i++)
{
current = dataChunk[i];
// many tests with 'current' and 'this->InvalidSequences'
self.Count[current]++;
self.ChunkSize++;
}
if (!UTF8Valid) self.InvalidSequences |= 1;
}
Run Code Online (Sandbox Code Playgroud)
我知道每个非静态成员函数都有自己的hidden this。我知道我会同时拥有隐藏的A * this和隐藏的A & self。我不知道很多东西是否this->someMember会比很多东西花费更多referenceToThis.someMember。
c++ ×4
file-io ×1
header-files ×1
optimization ×1
reference ×1
std ×1
string ×1
templates ×1
this ×1
vector ×1