【发布时间】:2016-11-23 14:54:44
【问题描述】:
今天在工作中,我遇到了一个我不理解的 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;
}
这段代码 sn-p 编译没有任何错误,并产生以下输出:
$ 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;时,为什么不代码编译? - 为什么大括号可以解决问题?
【问题讨论】:
标签: c++ most-vexing-parse