What is the lifetime of a temporary in something like func({someString, std::string("foo")})? I ask because the initializer_list in question is actually of type initializer_list<Foo> (not initializer_list<string>), and the ctor of Foo stores the address of its argument as a pointer. Will such temporaries be destructed after the initializer_list is created, but before the function call? Or will the temporaries always live for the duration of the function call?
Some sample code is provided below, along with the output produced by running the code with clang++ 8.0.0. The temporaries appears to live for the duration of the function call on my particular system, but is this behavior standard, and will it be consistent across different compilers?
#include <stdio.h>
#include <vector>
#include <string>
#include <initializer_list>
using namespace std;
class Foo
{
public:
const string* x;
Foo(const string& str) : x(&str) {
printf("Foo::Foo()\n");
}
~Foo() {
printf("Foo::~Foo()\n");
}
};
void
funcA(initializer_list<Foo> args)
{
(void)args;
printf("funcA()\n");
}
void
funcB(vector<Foo> args)
{
(void)args;
printf("funcB()\n");
}
void
funcC(const vector<Foo>& args)
{
(void)args;
printf("funcB()\n");
}
int
main()
{
string a;
printf("=========\n");
funcA({a, string("foo")});
printf("=========\n");
funcB({a, string("bar")});
printf("=========\n");
funcC({a, string("baz")});
printf("=========\n");
return 0;
}
Sample output:
=========
Foo::Foo()
Foo::Foo()
funcA()
Foo::~Foo()
Foo::~Foo()
=========
Foo::Foo()
Foo::Foo()
funcB()
Foo::~Foo()
Foo::~Foo()
Foo::~Foo()
Foo::~Foo()
=========
Foo::Foo()
Foo::Foo()
funcB()
Foo::~Foo()
Foo::~Foo()
Foo::~Foo()
Foo::~Foo()
=========
Aucun commentaire:
Enregistrer un commentaire