Sign in to follow this  

Initializer lists and smart pointers

This topic is 1107 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi!

I'm having a problem with some code not working as i whant it so, i've simplified an example:

#include <vector>
#include <initializer_list>
#include <memory>

class Test
{
public:
	typedef std::initializer_list<std::shared_ptr<int>> InitList_t;
	Test( InitList_t init ) :
		m_intVector( init.begin(), init.end() ) {}
	~Test() = default;

private:
	std::vector<std::shared_ptr<int>> m_intVector;
};

int main()
{
	// Works!
	Test t1( { 
		std::make_shared<int>( 1 ), 
		std::make_shared<int>( 2 ),
		std::make_shared<int>( 3 )
	} );

	// Does not work!
	auto t2 = std::make_unique<Test>( { 
		std::make_shared<int>( 1 ), 
		std::make_shared<int>( 2 ),
		std::make_shared<int>( 3 )
	} );

	// Works!
	auto t3 = std::make_unique<Test>( Test::InitList_t { 
		std::make_shared<int>( 1 ), 
		std::make_shared<int>( 2 ),
		std::make_shared<int>( 3 )
	} );

	return 0;
}

What i don't understand is why i have to tdefine the initializer list type when using unique_ptr, but not when not using them.

Can someone help me understand this please?

Share this post


Link to post
Share on other sites

This should work as well:

                                      vvvv
    auto t3 = std::make_unique<Test>( Test {
        std::make_shared<int>( 1 ),
        std::make_shared<int>( 2 ),
        std::make_shared<int>( 3 )
    } );

Creates an unnamed 'Test' rvalue, moves it into the unique pointer using Test's move-constructor.

Share this post


Link to post
Share on other sites

This topic is 1107 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this