2

A similar, maybe the same, question has been asked here: force const storing of returned by value value

However, much of the discussion was focused on "Why would you do that?"

Let's say I have struct A and B that both contain a shared_pointer. Now I have class C. Class C contains an instance of A. C has a const method getB() that return an object of type B, created on the moment and that contains a copy of the shared_pointer of A. However, I would like that whoever called getB() could not modify the content of B, especially the area of memory pointed by the shared_pointer.

In my user case, I am not in the position to modify class A and class B (which happen to be IplImage and cv::Mat of Opencv)

Is the only way to obtain my target to return a newly created B const *? (In this respect, this is a very useful answer)

Community
  • 1
  • 1
Antonio
  • 19,451
  • 13
  • 99
  • 197
  • I'm not a C++ guru, but it seems that what you want is a frozen object, not a const pointer... – fortran Aug 06 '13 at 12:57
  • @fortran What he seems to want doesn't make sense. C++ uses value semantics, so you can always copy the returned value to a non-const variable, and modify that. – James Kanze Aug 06 '13 at 13:01
  • Why can't you return a const reference? – Mikhail Aug 06 '13 at 13:03
  • @Mikhail: Because it can be copied. – Andrew Aug 06 '13 at 13:05
  • @Mikhail Because I would like class C not to contain an instance of class B. What getB() has to return depends on the current value of the instance of A belonging to C. If my class had 2 members `A m_a;` and `B m_b`, I would have to maintain m_b to be changed at each change of m_a. Updating m_b when getB() is called would make my method not const anymore. – Antonio Aug 06 '13 at 13:09
  • @Andrew What does "return an object of type B, created on the moment" mean? If the new `B` object is created, who's gonna delete it? – Mikhail Aug 06 '13 at 13:11
  • @Mikhail a copy is returned. `Foo someMethod() {return Foo();}` – Andrew Aug 06 '13 at 13:17
  • @Mikhail To guarantee deletion, I can return a `boost::shared_ptr`. This shouldn't be an issue. – Antonio Aug 06 '13 at 13:17

1 Answers1

2

You can use proxy pattern: http://www.oodesign.com/proxy-pattern.html

Create a proxy of B that will control access to it and return a proxy instead of B itself from your method.

class BProxy
{
public:
    BProxy(const B &b) : _b(b) {}

    void doSomeStuff() {...}    

private:
    B _b;
};
Andrew
  • 24,218
  • 13
  • 61
  • 90