[英]Why I am able to assign constant shared_ptr to non constant shared_ptr in C++?
我以為我不能將常量shared_ptr
分配給非常量shared_ptr
。 但令人驚訝的是,我能夠分配如下,它工作正常。
#include <iostream>
#include <memory>
using namespace std;
int main()
{
const std::shared_ptr<const string> a = std::make_shared<const string>("Hello world");
std::shared_ptr<const string> b = a;
cout << "a count " << a.use_count() << ", b count " << b.use_count() << endl;
return 0;
}
.use_count()
打印為2.任何人都可以幫助我理解我是如何做到的嗎?
代碼中的情況與此處完全相同:
const int a = 5;
int b = a;
std::cout << "a=" << a ", b=" << b << std::endl; // a=5, b=5
b = 10;
std::cout << "a=" << a ", b=" << b << std::endl; //a=5, b=10
不是特別令人驚訝,對吧? 我有const int
,我用它來初始化非const int
。 從價值a
得到復制到b
和a
沒有被修改的。
const std::shared_ptr
。 復制構造另一個對象不會修改原始對象。
use_count
可以更改,因為它不是std::shared_ptr
類的成員。 std::shared_ptr
需要在堆上分配兩個內存塊 - 一個控制塊和一個實際的對象塊。
每個std::shared_ptr
實例只存儲一個指向控制塊和實際對象的指針。 控制塊存儲使用計數(保存指向它的指針的std::shared_ptr
的數量)。
復制std::shared_ptr
,它會增加控制塊中的使用計數並獲得相同的兩個指針。 當std::shared_ptr
死亡時,它會減少使用計數(如果使用計數達到0,則刪除兩個塊)。
因此,總結一下:use count不是std::shared_ptr
的成員,因此它甚至可以改變const std::shared_ptr
(否則const std::shared_ptr
將毫無用處)。
在兩種情況下, a
和b
指向的string
仍然是const
,但是指針b
不是,所以你可以改變b
指向的內容:
std::shared_ptr<const string> b = a;
b = std::make_shared<const string>("New string");
但你不能改變a
正指向(因為a
是const
):
a = std::make_shared<const string>("Won't compile");
同理:
const char* const a = "Hello world";
const char* b = a;
const char* c = "Something else";
b = c; // the pointer "b" is not const and can be changed
// a = c; // won't compile since the pointer "a" itself is const
讓我們簡化一下:
#include <iostream>
#include <memory>
int main() {
const auto a = std::make_shared<const std::string>("Hello world");
auto b = a;
std::cout << "a count " << a.use_count() << ", b count " << b.use_count() << "\n";
}
允許來自可變對象的復制構造的類型,但不是來自常量對象的類型,是非常罕見的並且都是用戶定義的。 大多數情況下,它們都是早期的移動語義,因此也就是C ++ 11。
與C ++ 11一起引入的std::shared_ptr
並不是一個例外。 為什么要這樣?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.