I want to do the same thing as std::quote with a custom type, but I thinking about miss used of this kind of API with a temporary rvalue. After some dinging with std::quoted, I discovered the following problem:
To be efficient std::quoted force to store a const reference or a pointer to avoid a deep copy of the source object, but there are no mechanism to avoid to store the quoted result. If we store it, then delete the source object, and finally stream the stored result we try to access to the deleted reference or pointer.
The example below try to illustrate the problem:
#include <string>
#include <iostream>
#include <iomanip>
class String
{
public:
explicit String(const std::string & s) : _s(s) {std::cout << "String\n";}
~String() { std::cout << "~String\n"; _s = "ERROR TRY ACCESS DELETED STRING";}
const std::string & getS() const {return _s;}
private:
std::string _s;
};
int main()
{
std::cout << std::quoted(String("test").getS()) << '\n';
std::cout << '\n';
auto q = std::quoted(String("test").getS());
std::cout << q << '\n';
return 0;
}
This example print:
String
"test"
~String
String
~String
"p DELETED STRING"
We can see the same problem with gcc(trunk) and clang(trunk).