Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当类对象为常量时,使类中的共享\u ptr无法更改它指向的对象_C++_Pointers_Dynamic_Constants_Shared - Fatal编程技术网

C++ 当类对象为常量时,使类中的共享\u ptr无法更改它指向的对象

C++ 当类对象为常量时,使类中的共享\u ptr无法更改它指向的对象,c++,pointers,dynamic,constants,shared,C++,Pointers,Dynamic,Constants,Shared,我正在创建一个使用动态内存在多个对象之间共享数据的类。课程的相关部分如下所示 class StrBlob { public: StrBlob::StrBlob(std::initializer_list<std::string> il) : data(std::make_shared<std::vector<std::string>>(il)) {} void push_back(const std::string &t

我正在创建一个使用动态内存在多个对象之间共享数据的类。课程的相关部分如下所示

class StrBlob
{
public:
    StrBlob::StrBlob(std::initializer_list<std::string> il) :
        data(std::make_shared<std::vector<std::string>>(il)) {}
    void push_back(const std::string &t) const { data->push_back(t); }

private:
    std::shared_ptr<std::vector<std::string>> dataPtr;
};

通过使StrBlob对象为常量来使基础向量为常量是可能的还是可取的?当对象为const时,应该类似于将dataPtr设置为指向const的指针,但我不确定如何实现这一点。

您可以在
std::shared\u ptr
周围创建一个薄包装器(详细信息如ctor等):

#包括
模板类常数传播的共享的ptr{
std::共享_ptr m_ptr;
公众:
T&运算符*(){返回m_ptr.运算符*();}
T*运算符->(){返回m_ptr.运算符->();}
常量T&运算符*()常量{return m_ptr.运算符*();}
常量T*运算符->()常量{return m_ptr.运算符->();}
};
福巴级{
const_传播_共享_ptr m_ptr;
公众:
void f1(){*m_ptr=10;}
void f2()常量{*m_ptr=10;}//编译错误
};
但由于这是类的实现细节(在本例中是Foobar),我不确定这是否会更糟糕,因为让通过const方法修改数据或不修改数据可以由类设计器控制。

您需要类似的东西。不幸的是,这只是目前的一个建议。
//The result is foo = {"bar", "foobar"}
const StrBlob foo = {"bar"};
foo.push_back("foobar");
#include <memory>

template< class T > class const_propagated_shared_ptr {
    std::shared_ptr<T> m_ptr;
public:
    T &operator*() { return m_ptr.operator*(); }
    T* operator->() { return m_ptr.operator->(); }
    const T &operator*() const { return m_ptr.operator*(); }
    const T *operator->() const { return m_ptr.operator->(); }
};

class Foobar {
    const_propagated_shared_ptr<int> m_ptr;
public:
    void f1() { *m_ptr = 10; }
    void f2() const { *m_ptr = 10; } // compile error
};