将下面的代码不会用gcc编译:
struct test {
int x;
test() try : x{123} {
}
catch (...) {
}
};
int main() {}
Run Code Online (Sandbox Code Playgroud)
错误:
prog.cpp:3:25: error: expected unqualified-id before ‘{’ token
test() try : x{123} {
^
prog.cpp:5:5: error: expected unqualified-id before ‘catch’
catch (...) {
^
prog.cpp: In constructor ‘test::test()’:
prog.cpp:3:23: error: expected ‘{’ at end of input
test() try : x{123} {
^
prog.cpp:3:23: error: expected ‘catch’ at end of input
prog.cpp:3:23: error: expected ‘(’ at end of input …Run Code Online (Sandbox Code Playgroud) 基本上,我想知道为什么编译器拒绝ptr2声明:
int main() {
// this one works
decltype(void())* ptr1;
// this one does not
decltype(void{})* ptr2;
}
Run Code Online (Sandbox Code Playgroud)
如果您认为这是一个函数指针,请查看此代码ptr1:
#include <iostream>
using namespace std;
template <class T>
void f(T t) {
cout << __PRETTY_FUNCTION__ << endl;
}
int main() {
decltype(void())* ptr;
f(ptr);
}
Run Code Online (Sandbox Code Playgroud)
输出是void f(T) [with T = void*].
以下是我提出的情况:
#include <iostream>
using namespace std;
struct test {
test() { cout << "ctor" << endl; }
test(const test&) = delete;
test(test&&) = delete;
};
auto f() -> test {
return {};
// return test{};
}
auto main() -> int {
f();
}
Run Code Online (Sandbox Code Playgroud)
这段代码用clang和gcc编译,但是当我return {}改为return test{}它时就不再编译了.这是为什么?两种情况下它不应该一样吗?坦率地说,我不知道是否有一个很好的用例,但它让我感到意外,所以现在我想知道发生了什么.
这就是我想要做的:
// base case
void f() {}
template <typename T, typename... Ts>
void f() {
// do something with T
f<Ts...>();
}
int main() {
f<int, float, char>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它不编译:
prog.cpp: In instantiation of ‘void f() [with T = char; Ts = {}]’:
prog.cpp:6:5: recursively required from ‘void f() [with T = float; Ts = {char}]’
prog.cpp:6:5: required from ‘void f() [with T = int; Ts = {float, char}]’
prog.cpp:10:25: required from here
prog.cpp:6:5: error: no matching function …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,创建nested对象的行仅打印带有gcc的 "constructor" ,但不打印VS 2013:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return …Run Code Online (Sandbox Code Playgroud)