我对返回的字符串有一些问题:我有一个返回字符串的函数:
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();
}
};
当我抛出MyException
作为foo
函数返回的参数时出现问题:
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
^
如果我只是将返回的字符串放在变量中:
std::string msg = foo("blabla");
throw MyException(msg);
它工作正常(没有错误),为什么?如何解决这个问题?
答案 0 :(得分:4)
Rvalues不绑定到非const左值引用。更改构造函数:
MyException(std::string const & msg)
// ^^^^^
在现代C ++中,您甚至可以按值获取字符串:
MyException(std::string msg) noexcept : m_msg(std::move(msg)) { }
这样做的另一个好处是,与原始代码不同,可以构建异常类,而不会抛出异常。