[英]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.