C ++ abstract data types return without dangling pointers

Hello,

I come from the background of C # and do not have much experience in C ++. To create clean code, I try to separate implementation and interfaces and use inheritance whenever possible. And when I tried to apply typical C # concepts to C ++, I had a problem that I could not solve yet. I guess this is probably trivial for an experienced C ++ programmer, but he drove me crazy for quite some time.

First I declare a base class (it does not contain logic at the moment, but in the future)

class PropertyBase : public IProperty
{
};

Then I define the interface for the properties

class IProperty
{
public:
    virtual ~IProperty() {};
    virtual PropertyBase    correct(const ICorrector &corrector) = 0;
    virtual PropertyBase    joinWith(const PropertyBase &partner, const IRecombinator &recombinator) = 0;
};

: , , , . , PropertyBase. , PropertyBase, .

, , IProperty , :

class IProperty
{
public:
    virtual ~IProperty() {};
    virtual PropertyBase*   correct(const ICorrector &corrector) = 0;
    virtual PropertyBase*   joinWith(const PropertyBase &partner, const IRecombinator &recombinator) = 0;
};

, , . , - .

+5
5

, . , . .

class IProperty
{
public:
    virtual ~IProperty() {};
    virtual std::unique_ptr<PropertyBase> correct(const ICorrector &) = 0;
    virtual std::unique_ptr<PropertyBase> joinWith(const PropertyBase &,
                                                   const IRecombinator &) = 0;
};

:

std::unique_ptr<PropertyBase> pb(property.correct(corrector));
// use pb and forget about it; smart pointers do their own cleanup

, , :

std::shared_ptr<PropertyBase> pb(property.correct(corrector));

. MSDN unique_ptr, shared_ptr.

+5

, , , ++.

, , ++, ad-hoc-. , . , "" .

: , . , class Base { int x; } class Derived : public Base { int y; }. :

Base Function() { Derived d; return d; }
...
Base b = Function();

b Derived, " " a Base. b Base. "" Derived Base b.

++ ad-hoc-. # , ++, , #, .

+2

. , , . shared_ptr boost ++ 0x.

0

, - ++, . ++ " ++" Exceptional ++ .

0

. , .

:

class A : public Base
{
public:
   Base *correct(const I &c) 
     { p2 = do_something(c); return &p2; }
   ...
private:
   A2 p2;
};

, , p2 . , , . unique_ptr shared_ptr, .

, , () . , , :

class B : public Base
{
public:
   Base *correct(const I &c) {
      switch(c.get_bool()) {
         case false: p3 = do_something_else(c); return &p3;
         case true: p4 = do_something(c); return &p4;
      };
   }
 private:
    B3 p3;
    B4 p4;
};

p3 p4 B .

0

All Articles