1 /* Class autosprintf - formatted output to an ostream.
2 Copyright (C) 2002, 2013, 2015 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2002.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Tell glibc's <stdio.h> to provide a prototype for vasprintf().
19 This must come before <config.h> because <config.h> may include
20 <features.h>, and once <features.h> has been included, it's too late. */
22 # define _GNU_SOURCE 1
26 #include "autosprintf.h"
31 #include "lib-asprintf.h"
33 /* std::swap() is in <utility> since C++11. */
34 #if __cplusplus >= 201103L
43 /* Constructor: takes a format string and the printf arguments. */
44 autosprintf::autosprintf (const char *format, ...)
47 va_start (args, format);
48 if (vasprintf (&str, format, args) < 0)
53 /* Copy constructor. Necessary because the destructor is nontrivial. */
54 autosprintf::autosprintf (const autosprintf& src)
56 str = (src.str != NULL ? strdup (src.str) : NULL);
59 /* Copy constructor. Necessary because the destructor is nontrivial. */
60 autosprintf& autosprintf::operator = (autosprintf copy)
62 std::swap (copy.str, this->str);
66 /* Destructor: frees the temporarily allocated string. */
67 autosprintf::~autosprintf ()
72 /* Conversion to string. */
73 autosprintf::operator char * () const
77 size_t length = strlen (str) + 1;
78 char *copy = new char[length];
79 memcpy (copy, str, length);
85 autosprintf::operator std::string () const
87 return std::string (str ? str : "(error in autosprintf)");