首页 > 解决方案 > Different behavior when passing exception by value vs by reference C++

问题描述

So I understand the basic concept of passing by value or reference. In this example I'm trying to catch an exception either by value or by reference:

#include <iostream>
int main() {
    try {
        throw std::invalid_argument("nope");
    } catch(std::exception &e) {
        std::cout << e.what() << std::endl;
    }
}

Outputs: "nope"

#include <iostream>
int main() {
    try {
        throw std::invalid_argument("nope");
    } catch(std::exception e) {
        std::cout << e.what() << std::endl;
    }
}

(notice the missing &) Outputs: "std::exception"

Shouldn't I get the same output given that the second version "copies" e?

标签: c++pointers

解决方案


推荐阅读