make_shared (<memory>)

创建并返回使用默认值分配程序,指向分配的对象从零个或多个参数构造 shared_ptr

template<class Type, class... Types>
    shared_ptr<Type> make_shared(
        Types&&... _Args
    );

参数

Parameter

描述

_Args

构造函数参数。函数推断要构造超加载调用根据提供的参数。

属性值/返回值

返回指向分配的对象的 shared_ptr

备注

函数创建对象 shared_ptr<Type>,对 Type(_Args...) 的指针为已分配和构造按默认值分配程序 allocator()。下面的示例演示如何创建共享指针到类型通过调用特定构造函数超负载。

示例

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class Zebra
{
private:
    int nStripes;
    string name;
public:
    Zebra() : nStripes(-1), name("Default")
    {
        cout << "I'm a default Zebra." << endl;
    }

    Zebra(int i, string s) : nStripes(i), name(s)
    {
        
        std::cout << "My name is " << name 
                  << " and I have " << nStripes 
                  << " stripes." << endl;
    }

    virtual ~Zebra()
    {
        cout << "Goodbye from " << name << endl;


    }

};

void MakeZebras()
{
    auto pzeb = make_shared<Zebra>();
    auto pGeorge = make_shared<Zebra>(5, "George");
}



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(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;
    }


};

shared_ptr<Song> MakeSongPtr(wstring artist, wstring title)
{
    Song* s = new Song(artist, title);
    shared_ptr<Song> p(s);
    //return make_shared<Song>(artist,title);
    return p;
}

要求

标头: <memory>

命名空间: std

请参见

参考

<memory>

shared_ptr Class