ATLAS Offline Software
Loading...
Searching...
No Matches
StrFormat.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
3*/
4
5// $Id: StrFormat.cxx 579482 2014-01-22 09:14:16Z krasznaa $
12
13#include "CxxUtils/StrFormat.h"
14
15// c includes
16#include <stdarg.h>
17#include <stdio.h>
18#include <stdlib.h>
19#include <stdexcept>
20
21namespace {
22 // little helper to ensure a char* is freed
23 class CharLiberator
24 {
25 char* m_buf;
26
27 public:
28 explicit
29 CharLiberator(char* buf) : m_buf(buf)
30 {}
31 CharLiberator() : m_buf (NULL)
32 {}
33 ~CharLiberator()
34 {
35 free(m_buf);
36 }
37
38 CharLiberator (const CharLiberator&) = delete;
39 CharLiberator& operator= (const CharLiberator&) = delete;
40 };
41
42}
43
44namespace CxxUtils {
45
48std::string
49strformat(const char* fmt, ...)
50{
51 char *buf = NULL;
52 int nbytes = -1;
53
54 va_list ap;
55 va_start(ap, fmt); /* Initialize the va_list */
56
57 nbytes = vasprintf(&buf, fmt, ap);
58 va_end(ap); /* Cleanup the va_list */
59
60 if (nbytes < 0) {
61 /*buf is undefined when allocation failed
62 * see: http://linux.die.net/man/3/asprintf
63 */
64 // free(buf);
65 throw std::runtime_error("problem while calling vasprintf");
66 }
67
68 CharLiberator guard(buf);
69
70 // help compiler to apply RVO
71 return std::string(buf);
72}
73
74} //> namespace CxxUtils
75
Provide helper functions to create formatted strings.
const char *const fmt
std::string strformat(const char *fmt,...)
return a std::string according to a format fmt and varargs
Definition StrFormat.cxx:49