make_shared (<memory>)
Creates and returns a shared_ptr that points to the allocated objects that are constructed from zero or more arguments by using the default allocator.
template<class Type, class... Types>
shared_ptr<Type> make_shared(
Types&&... _Args
);
Parameters
Parameter |
Description |
---|---|
_Args |
Constructor arguments. The function infers which constructor overload to invoke based on the arguments that are provided. |
Property Value/Return Value
Returns a shared_ptr that points to the allocated object.
Remarks
The function creates the object shared_ptr<Type>, a pointer to Type(_Args...) as allocated and constructed by the default allocator allocator(). The following example shows how to create shared pointers to a type by invoking specific constructor overloads.
Example
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class SongBase
{
protected:
std::wstring id;
public:
SongBase() : id(L"default"){}
SongBase(std::wstring init) : id(init) {}
virtual ~SongBase(){}
};
class Song : public SongBase
{
public:
std::wstring title_;
std::wstring artist_;
std::wstring duration_;
std::wstring format_;
Song(std::wstring title, std::wstring artist) : title_(title), artist_(artist){}
Song(Song&& other)
{
title_ = other.title_;
artist_ = other.artist_;
duration_ = other.duration_;
format_ = other.format_;
other.title_ = nullptr;
other.artist_ = nullptr;
other.duration_ = nullptr;
other.format_ = nullptr;
}
~Song()
{
std::wcout << L"deleting " << title_ << L":" << artist_ << std::endl;
}
Song& operator=(Song&& other)
{
if(this != &other)
{
this->artist_ = other.artist_;
this->title_ = other.title_;
this->duration_ = other.duration_;
this->format_ = other.format_;
other.artist_ = nullptr;
other.title_ = nullptr;
other.duration_ = nullptr;
other.format_ = nullptr;
}
return *this;
}
bool operator ==(const Song& other)
{
return this->artist_.compare(other.artist_) == 0 &&
this->title_.compare(other.title_) == 0;
}
};
// we would need this helper function if we didn't have
// make_shared<Song>(artist, title) available.
shared_ptr<Song> MakeSongPtr(wstring artist, wstring title)
{
Song* s = new Song(artist, title);
shared_ptr<Song> p(s);
return p;
}
Requirements
Header: <memory>
Namespace: std