c++ - Protecting private member return by reference from accidental reassignment -


i have following function prototype:

virtual cbuffer& getdata(unsigned int& samples, unsigned int& stride); 

this returns reference cbuffer object private member of class.

the problem if following written, internal private member method returns reassigned.

cbuffer& cplug::processdata(unsigned int& samples, unsigned int& stride) {   /* data source */   cbuffer& buffer = m_source.getdata(samples, stride);    if (m_postprocess)     buffer = postprocess(buffer, samples, stride);    return buffer; } 

obviously can fixed doing following:

cbuffer& cplug::processdata(unsigned int& samples, unsigned int& stride) {   /* data source */   cbuffer* buffer = &m_source.getdata(samples, stride);    if (m_postprocess)     buffer = &postprocess(*buffer, samples, stride);    return *buffer; } 

but want know if there way prevent this, possibly through use of const unaware of?

at point of opinion should convert using pointers, nice know if done.

because sample says more thousand words, potentially: see live

#include <vector> #include <memory>  typedef std::vector<int> cbuffer;  static cbuffer& postprocess(cbuffer& data)  {      for(auto& el : data)         el /= 2;     return data; }  struct csource {     csource() : _data(std::make_shared<cbuffer>(10)) {}      std::shared_ptr<cbuffer>       getdata()       { return _data; }     std::shared_ptr<const cbuffer> getdata() const { return _data; }    private:     std::shared_ptr<cbuffer> _data; };  struct cplug {     cplug(bool postprocess = true) : m_postprocess(postprocess) { }      std::shared_ptr<const cbuffer> processdata() const     {         /* data source, implicitely const */         auto buffer = m_source.getdata();          if (!m_postprocess)             return buffer;          // clone!         auto clone = *buffer;         return std::make_shared<cbuffer>(postprocess(clone));     }    private:     bool    m_postprocess;     csource m_source; };  int main() {     cplug intance; } 

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -