C++标准库学习笔记(Shared Pointer)-3

声明:这个博文所有内容均来自于C++标准库-自学教程与参考手册(第二版)英文版 上册。如果转载,务必附带本声明,并注明出处。
smart pointer就是智能指针,它能够自动计数引用,并在最后一次引用后释放,包含于< memory>头文件。C++标准库-自学教程与参考手册(第二版)英文版Page76指出:
Since C, we know that pointers are important but are a source of trouble. One reason to use pointers is to have reference semantics outside the usual boundaries of scope. However, it can be very tricky to ensure that their lifetime and the lifetime of the objects they refer to match, especially when multiple pointers refer to the same object. For example, to have the same object in multiple collections (see Chapter 7), you have to pass a pointer into each collection, and ideally there should be no
problems when one of the pointers gets destroyed (no “dangling pointers” or multiple deletions of the referenced object) and when the last reference to an object gets destroyed (no “resource leaks”).
A usual approach to avoid these kinds of problems is to use “smart pointers.” They are “smart”in the sense that they support programmers in avoiding problems such as those just described. For example, a smart pointer can be so smart that it “knows” whether it is the last pointer to an object and uses this knowledge to delete an associated object only when it, as “last owner” of an object, gets destroyed. Note, however, that it is not sufficient to provide only one smart pointer class. Smart pointers can be smart about different aspects and might fulfill different priorities, because you might pay a price for the smartness. Note that with a specific smart pointer, it’s still possible to misuse a pointer or to program erroneous behavior.
自从C++11以后,C++标准库提供两种类型的 smart pointer: 一个是shared_ptr. 它使得多个smart pointer可以指向同一个object. 另一个是unique_ptr。 它是一种互斥的指针,使得一个object仅有一个smart pointer可以指向它。

include 
#include 
#include 
#include 

using namespace std;
int main()
{
    // two shared pointers representing two persons by their name
    shared_ptr<string> pNico(new string("nico"));  //这里使用了隐式转换,将普通 string 指针转换为了shared_ptr
    shared_ptr<string> pJutta(new string("jutta"));
    // capitalize person names
    (*pNico)[0] = 'N';
    pJutta->replace(0, 1, "J");
    // put them multiple times in a container
    vector<shared_ptr<string>> whoMadeCoffee;
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);
    // print all elements
    for (auto ptr : whoMadeCoffee) {
        cout << *ptr << " ";
    }
    cout <&l

你可能感兴趣的:(c++,c++)