C++有没有智能指针的区别的一个例子

一个类用的是智能指针指向的vector,一个类的用的是裸的vector. 在拷贝对象的时候出现不一样.

智能指针版:

#include 
#include 
#include 
#include 
#include 
    
using std::initializer_list;
using std::string;
using std::vector;
using std::make_shared;
    
class StrBlob {
public:
    StrBlob();
    StrBlob(std::initializer_list il);
    void push_back(const string &t) {data->push_back(t);}
    vector::size_type size() const {return data->size();}
private:
    std::shared_ptr> data;
};  
    
StrBlob::StrBlob(): data(make_shared>()) {}

StrBlob::StrBlob(initializer_list il): data(make_shared>(il)) {}

int main()
{   
    StrBlob b = {"hello"};
    StrBlob c = b;
    c.push_back("world");
    
    std::cout << b.size() << std::endl;
    return 0; 
}   

编译:

g++ -std=c++11 -Wall -o strblob_p405 strblob_p405.cpp

输出为: 2

由此可见,两个对象共用的是同一个底层的vector.

普通版:

#include 
#include 
#include 
#include 
#include 

using std::initializer_list;
using std::string;
using std::vector;
using std::make_shared;

class StrBlob {
public:
    StrBlob();
    StrBlob(std::initializer_list il);
    void push_back(const string &t) {data.push_back(t);}
    vector::size_type size() const {return data.size();}
private:
    std::vector data;
};

StrBlob::StrBlob(): data(vector()) {}

StrBlob::StrBlob(initializer_list il): data(vector(il)) {}

int main()
{
    StrBlob b = {"hello"};
    StrBlob c = b;
    c.push_back("world");

    std::cout << b.size() << std::endl;
    return 0;
}

输出为1, 两个对象b 和 c 分别使用各自的vector, 互不干扰.

 

参考: <> p405

你可能感兴趣的:(C++有没有智能指针的区别的一个例子)