c++ - C++ 代码可以在 C++03 和 C++11 中都有效但做不同的事情吗?

标签 c++ c++11 language-lawyer c++03

C++ 代码是否可以同时符合 C++03标准和 C++11标准,但根据编译的标准做不同的事情?

最佳答案

答案是肯定的。好的一面是:

  • 以前隐式复制对象的代码现在将尽可能隐式移动它们。

在消极方面,标准的附录 C 中列出了几个示例。尽管负面的比正面的多得多,但它们中的每一个都不太可能发生。

字符串字面量

#define u8 "abc"
const char* s = u8"def"; // Previously "abcdef", now "def"

#define _x "there"
"hello "_x // Previously "hello there", now a user defined string literal

0的类型转换

在 C++11 中,只有字面量是整数空指针常量:

void f(void *); // #1
void f(...); // #2
template<int N> void g() {
    f(0*N); // Calls #2; used to call #1
}

整数除法和取模后的舍入结果

在 C++03 中,允许编译器向 0 或向负无穷大舍入。在 C++11 中,强制向 0 舍入

int i = (-1) / 2; // Might have been -1 in C++03, is now ensured to be 0

嵌套模板右括号之间的空格>> vs >>

在特化或实例化中,>> 可能被解释为 C++03 中的右移。不过,这更有可能破坏现有代码:(来自 http://gustedt.wordpress.com/2013/12/15/a-disimprovement-observed-from-the-outside-right-angle-brackets/)

template< unsigned len > unsigned int fun(unsigned int x);
typedef unsigned int (*fun_t)(unsigned int);
template< fun_t f > unsigned int fon(unsigned int x);

void total(void) {
    // fon<fun<9> >(1) >> 2 in both standards
    unsigned int A = fon< fun< 9 > >(1) >>(2);
    // fon<fun<4> >(2) in C++03
    // Compile time error in C++11
    unsigned int B = fon< fun< 9 >>(1) > >(2);
}

运算符 new 现在可能会抛出 std::bad_alloc

以外的其他异常
struct foo { void *operator new(size_t x){ throw std::exception(); } }
try {
    foo *f = new foo();
} catch (std::bad_alloc &) {
    // c++03 code
} catch (std::exception &) {
    // c++11 code
}

用户声明的析构函数具有隐式异常规范 来自 What breaking changes are introduced in C++11? 的示例

struct A {
    ~A() { throw "foo"; } // Calls std::terminate in C++11
};
//...
try { 
    A a; 
} catch(...) { 
    // C++03 will catch the exception
} 

size() 个容器现在需要在 O(1) 中运行

std::list<double> list;
// ...
size_t s = list.size(); // Might be an O(n) operation in C++03

std::ios_base::failure 不再直接从 std::exception 派生

虽然直接基类是新的,但 std::runtime_error 不是。因此:

try {
    std::cin >> variable; // exceptions enabled, and error here
} catch(std::runtime_error &) {
    std::cerr << "C++11\n";
} catch(std::ios_base::failure &) {
    std::cerr << "Pre-C++11\n";
}

关于c++ - C++ 代码可以在 C++03 和 C++11 中都有效但做不同的事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047198/

相关文章:

c++ - [expr.reinterpret.cast]/6 下面的注释是什么意思?

c++ - void{} 是否合法?

c++ - 如何在 C++ Eigen 中设置 cg 矩阵近似中的最大迭代?

c++ - 在代码块中运行发布版本时出现段错误,但运行调试版本时不会出现段错误

C++ 如何将数组作为键插入到 unordered_map 中?

c++ - "Builder"函数模板

c++ - 三元运算符隐式转换为基类

C++:重载模板别名

c++ - 寻找正整数数组的最大权重子序列?

C++98 与 C++11 std::set::insert 规范