2

How does PyErr_SetString handle the passed in c-string? e.g. is it safe to do:

{
  int age = 12;
  std::stringstream ostr; ostr << "I'm " << age << " years old and what is this?";
  PyErr_SetString(PyExc_RuntimeError, ostr.str().c_str());
}

Obviously https://docs.python.org/2/c-api/exceptions.html#PyErr_SetString says that it's 'converted to a string object', but does that necessarily entail that the contents will be copied?

user
  • 4,920
  • 3
  • 25
  • 38
  • The behaviour of `std::string` is to copy the contents of any character string it is given. I doubt cpython would go against that behaviour. – Dunes Jul 27 '14 at 22:11

1 Answers1

2

It is safe to do so. Python copies the contents of the string before returning. This applies to other Python string operations as well.

In general, only references to Python objects (PyObject*) may be borrowed or stolen, and unless otherwise specifically specified, the interpreter copies the arguments.

sterin
  • 1,898
  • 15
  • 13