Following the last answer in the recommended link
How can I make new[]
default-initialize the array of primitive types?,
I came up with the following small example:
#include <iostream>
#include <memory>
#include <string>
class Widget {
private:
std::string _name;
public:
Widget(const char *name): _name(name) { }
Widget(const Widget&) = delete;
const std::string& name() const { return _name; }
};
int main()
{
const int n = 3;
std::unique_ptr<Widget[]> ptrLabels(
new Widget[n]{
Widget("label 1"),
Widget("label 2"),
Widget("label 3")
});
for (int i = 0; i < n; ++i) {
std::cout << ptrLabels[i].name() << '\n';
}
return 0;
}
Output:
label 1
label 2
label 3
Live Demo on coliru
The trick is to use an initializer list.
I was a bit unsure whether this involves copy construction (which is often forbidden in widget class libaries). To be sure, I wrote Widget(const Widget&) = delete;
.
I have to admit that this works with C++17 but not before.
I fiddled a bit with the first example.
I tried also
new Widget[n]{
{ "label 1" },
{ "label 2" },
{ "label 3" }
});
with success until I realized that I forgot to make the constructor explicit
in first example. (Usually, a widget set wouldn't allow this – to prevent accidental conversion.) After fixing this, it didn't compile anymore.
Introducing, a move constructor it compiles even with C++11:
#include <iostream>
#include <memory>
#include <string>
class Widget {
private:
std::string _name;
public:
explicit Widget(const char *name): _name(name) { }
Widget(const Widget&) = delete;
Widget(const Widget &&widget): _name(std::move(widget._name)) { }
const std::string& name() const { return _name; }
};
int main()
{
const int n = 3;
std::unique_ptr<Widget[]> ptrLabels(
new Widget[n]{
Widget("label 1"),
Widget("label 2"),
Widget("label 3")
});
for (int i = 0; i < n; ++i) {
std::cout << ptrLabels[i].name() << '\n';
}
return 0;
}
Output: like above
Live Demo on coliru