今天上班时我遇到了一个我不懂的C ++行为。我已经制作了以下示例代码来说明我的问题:
#include <string>
#include <iostream>
class MyException
{
public:
MyException(std::string s1) {std::cout << "MyException constructor, s1: " << s1 << std::endl;}
};
int main(){
const char * text = "exception text";
std::cout << "Creating MyException object using std::string(const char *)." << std::endl;
MyException my_ex(std::string(text));
std::cout << "MyException object created." << std::endl;
//throw my_ex;
std::string string_text("exception text");
std::cout << "Creating MyException object using std::string." << std::endl;
MyException my_ex2(string_text);
std::cout << "MyException object created." << std::endl;
// throw my_ex2;
return 0;
}
此代码段编译时没有任何错误,并产生以下输出:
$ g++ main.cpp
$ ./a.out
Creating MyException object using std::string(const char *).
MyException object created.
Creating MyException object using std::string.
MyException constructor, s1: exception text
MyException object created.
请注意,对于my_ex
,我没有调用我定义的构造函数。接下来,如果我想实际抛出这个变量:
throw my_ex;
我收到编译错误:
$ g++ main.cpp
/tmp/ccpWitl8.o: In function `main':
main.cpp:(.text+0x55): undefined reference to `my_ex(std::string)'
collect2: error: ld returned 1 exit status
如果我在转换中添加大括号,请执行以下操作:
const char * text = "exception text";
std::cout << "Creating MyException object using std::string(const char *)." << std::endl;
MyException my_ex((std::string(text)));
std::cout << "MyException object created." << std::endl;
throw my_ex;
然后它按照我的预期运作:
$ g++ main.cpp
$ ./a.out
Creating MyException object using std::string(const char *).
MyException constructor, s1: exception text
MyException object created.
terminate called after throwing an instance of 'MyException'
Aborted (core dumped)
我有以下问题:
throw my_ex;
?答案 0 :(得分:34)
根据most vexing parse,MyException my_ex(std::string(text));
是一个函数声明;该函数名为my_ex
,使用类型为text
的名为std::string
的参数,返回MyException
。它根本不是对象定义,因此不会调用构造函数。
请注意undefined reference to 'my_ex(std::string)'
的错误消息throw my_ex;
(您实际上是在尝试抛出一个函数指针),这意味着无法找到函数my_ex
的定义。
要修复它,您可以添加其他括号(如您所示)或使用C ++ 11支持的braces:
MyException my_ex1((std::string(text)));
MyException my_ex2{std::string(text)};
MyException my_ex3{std::string{text}};
答案 1 :(得分:4)
答案是尽可能使用{}
(braced-init)。但有时候,它可能会无意中错过。幸运的是,编译器(如没有额外警告标志的clang)可以暗示:
warning: parentheses were disambiguated as a function declaration [-Wvexing-parse]
MyException my_ex(std::string(text));
^~~~~~~~~~~~~~~~~~~
test.cpp:13:23: note: add a pair of parentheses to declare a variable
MyException my_ex(std::string(text));
^
( )
1 warning generated.
会立即向您发出问题。