how create an object then add it to vector of unique ptr
if I have a vector of unique_ptr like this:
std::vector<unique_ptr<item>> item_list;
and I wanted to create objects then adding them how to do it:
1 2 3
|
item i;
i.name = 'name';
item_list.push_back(i);
|
Cant find an example of this normally example look like this:
item_list.emplace_back(new item());
or
item_list.emplace_back(std::make_unique<item>());
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <vector>
#include <memory>
struct item
{
item( int a, double b ) { /* ... */ } // 1
item( const char* cstr ) { /* ... */ } // 2
// ...
};
int main()
{
std::vector< std::unique_ptr<item> > item_list ;
item_list.push_back( std::make_unique<item>( 23, 45.67 ) ) ; // constructor 1
item_list.push_back( std::make_unique<item>( "abcdefgh" ) ) ; // constructor 2
}
|
Alternatively, you could use std::move
, if you want to create the object before adding it to the container.
Topic archived. No new replies allowed.