#include <string.h>
#include <stdio.h>
#include <stdlib.h>
class A {
public:
A(char* buf, int len, bool own)
: buf_(own? new char[len_] : buf_)
// Note that the above expression either uses `len_` (which is
// not yet initialized), or buf_ (which is the variable we are
// trying to initialize). In both cases, the parameter
// (len or buf) should have been used.
, len_(len)
, own_(own) {
printf("buf=%p, buf_=%p\n", buf, buf_);
if(own_) memcpy(buf_, buf, len);
}
~A() {
printf("%02x\n", buf_[0]);
if(own_) delete[] buf_;
}
private:
char* const buf_;
int const len_;
bool const own_;
};
int main() {
char buf[100] = {0};
A a(buf, (int)sizeof(buf), true);
return 0;
}
显然,行:
buf_(拥有?new char [len_]:buf _)
使用未初始化的值len_和buf _。
我按
编译g ++ a.cpp -Wall -Wextra -Wunused-but-set-parameter -Winit-self -Wmaybe-未初始化
让我感到困惑的是gcc没有报告有关未初始化成员buf_
和len_
的任何警告。
在这种情况下,哪个gcc选项会产生警告?
更新
g ++ - 6没有警告,g ++ - 7 -O1警告len_,g ++ - 8 -O0和clang ++ 警告len_和buf_。 - Marc Glisse