【问题标题】:Const correctness and shared_ptr conversionsconst 正确性和 shared_ptr 转换
【发布时间】:2016-01-21 12:22:28
【问题描述】:

假设我有以下类型:

using pointer = std::shared_ptr<MyType>;
using pointer_to_const = std::shared_ptr<const MyType>;

现在,如果我有如下代码:

void fun(pointer_to_const ptr);

pointer myObj = SomeFactoryMethod();
fun(myObj);

pointerpointer_to_const 之间是否存在自动转换?如果有,在此转换过程中是否会复制底层 MyType 对象?

因为如果有转换,并且没有副本,那么在多线程上下文中,另一个线程可以使用原始的myObj 指针来修改底层对象,从而违反const 所期望的fun

【问题讨论】:

    标签: c++ multithreading c++11 constants shared-ptr


    【解决方案1】:

    是的,可以进行这样的转换,并且将是指针和控制块(引用计数)的浅拷贝。

    【讨论】:

      【解决方案2】:

      是的,这会起作用。将调用shared_ptr 的以下构造函数:

      template< class Y > 
      shared_ptr( const shared_ptr<Y>& r );
      

      Y 推导出为const MyType

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-24
        • 2017-08-06
        • 2018-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-16
        相关资源
        最近更新 更多