【发布时间】:2015-02-06 00:56:18
【问题描述】:
我发现了一个示例,其中输出因优化设置而异(-O3 与无),但 GCC 4.8.2 不会产生警告,即使使用 -std=c++11 -Wall -pedantic 选项也是如此。
在这种特殊情况下,我假设“忘记”header.h 中的注释行是一个错误,而对于 -O3,c<int>::get() 会被内联。
但是,有什么方法可以保护自己免受此类错误的影响——也许是编译器或链接器选项?
header.h:
#ifndef HEADER_H
#define HEADER_H
template<class T>
struct c
{
int get() { return 0; }
};
// template<> int c<int>::get();
#endif
imp.cpp:
#include "header.h"
template<>
int c<int>::get()
{
return 1;
}
main.cpp:
#include <iostream>
#include "header.h"
int main()
{
c<int> i;
std::cout << i.get() << '\n'; // prints 0 with -O3, and 1 without
}
构建:
c++ -std=c++11 -pedantic -Wall -O3 -c imp.cpp
c++ -std=c++11 -pedantic -Wall -O3 -c main.cpp
c++ -std=c++11 -pedantic -Wall -O3 imp.o main.o
【问题讨论】:
-
行为有何不同?