C++ C++;由于返回字符串,异常构造函数错误

C++ C++;由于返回字符串,异常构造函数错误,c++,throw,C++,Throw,我对返回的字符串有一些问题:我有一个返回字符串的函数: std::string foo(const std::string& paramIn) { return ("My message" + paramIn); } 我有一个例外类: class MyException : public std::exception { private: std::string m_msg; public: MyException(std::string& msg) : m_ms

我对返回的字符串有一些问题:我有一个返回字符串的函数:

std::string foo(const std::string& paramIn)
{
  return ("My message" + paramIn);
}
我有一个例外类:

class MyException : public std::exception
{
private:
  std::string m_msg;

public:
  MyException(std::string& msg) : m_msg(msg) {}
  virtual ~MyException() throw() {}

  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};
当我抛出一个以
foo
函数返回值为参数的
MyException
时,问题出现了:

throw MyException(foo("blabla"));
它说:

/home/me/my_proj/main.cpp: In member function ‘std::string ConfigFile::getClassifierExtractorType()’:
/home/me/my_proj/main.cpp:79:96: error: no matching function for call to ‘MyException::MyException(std::string)’
     throw MyException(foo("blabla"));
                                    ^
/home/me/my_proj/main.cpp:79:96: note: candidates are:
In file included from /home/me/my_proj/main.hpp:5:0,
                 from /home/me/my_proj/main.cpp:1:
/home/me/my_proj/CMyExceptions.hpp:38:3: note: MyException::MyException(std::string&)
   MyException(std::string& msg) : m_msg(msg) {}
   ^
/home/me/my_proj/CMyExceptions.hpp:38:3: note:   no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘std::string& {aka std::basic_string<char>&}’
/home/me/my_proj/CMyExceptions.hpp:32:7: note: MyException::MyException(const MyException&)
 class MyException : public MyIOException
       ^

它工作正常(没有错误),为什么?如何解决此问题?

右值不绑定到非常量左值引用。更改构造函数:

MyException(std::string const & msg)
//                      ^^^^^
在现代C++中,你甚至可以按值:
MyException(std::string msg) noexcept : m_msg(std::move(msg)) { }

这还有一个额外的优点,即与原始代码不同,可以构造异常类而不引发异常。

右值不绑定到非常量左值引用。更改构造函数:

MyException(std::string const & msg)
//                      ^^^^^
在现代C++中,你甚至可以按值:
MyException(std::string msg) noexcept : m_msg(std::move(msg)) { }

这还有一个额外的优点,即与原始代码不同,可以构造异常类而不引发异常。

我还尝试更改
const std::string foo(const std::string¶mIn)
,但事实并非如此worked@thedarksideofthemoon:const-rvalue也不绑定到非const-lvalue引用。还有什么其他更改可以修复它(没有
noexcept
)?@thedarksideofmon:完全按照我在第一个代码段中所说的做。在ctor中使用值总是可能的,不是吗?效率更低(没有移动,没有右值引用)。我也尝试过更改
const std::string foo(const std::string¶mIn)
,但没有worked@thedarksideofthemoon:常量值也不绑定到非常量左值引用。还有什么其他更改可以修复它(没有
noexcept
)?@thedarksideofmon:完全按照我在第一段代码中所说的去做。在ctor中使用一个值总是可能的,不是吗?效率较低(无移动,无右值引用)。构造函数参数应为
const字符串&
构造函数参数应为
const字符串&