How reasonable is it to place new'd objects in the constructor initializer?

Is it wise or stupid to pass new objects in the constructor initializer?

For instance:

class Mallard
{
public:
  Mallard()
   : s(new SomeLargeObject(5)) {}
private:
  SomeLargeObject * s;
};
+3
source share
3 answers

In your code example, nothing is mechanically broken if the destructor that you forgot to publish performs symmetric deletion.

Although conditionally (more secure and less boilerplate) you need something like

#include <memory>

class Mallard {
    std::unique_ptr<SomeLargeObject> that_;
public:
     Mullard(): that_(new SomeLargeObject)
     {}
     // this way you don't need to code the destructor
};

: (@Praetorian, @RemyLebeau, @AdrianMcCarthy), , , , . std::unique_ptr ( ).

+5

2 :

Cent # 1: , s SomeLargeObject ;

Cent # 2: , , , . , Bridge Pattern :

// Abstract base of all beaks
class Beak
{
  public:
};

// Abstract base of all birds
class Bird
{
  protected: 
    const Beak *beak;

    ~Bird()
    {
        delete beak;
    }
};

class MallardBeak : public Beak
{
};

class Mallard : public Bird
{
  public:
    Mallard() : beak(new MallardBeak) { }
};

class PigeonBeak : public Beak
{
};

class Pigeon : public Bird
{
  public:
    Pigeon() : beak(new PigeonBeak) { }
};
+1

- , ++ (, Java), ( ) . , - , .

, , , (, , ? , .

Again, be very careful and check out some methods that protect you from such errors and unwanted situations, such as Smart Pointers that use the RAII idiom. (The Boost Libraries collection has a number of great implementations, providing you with a lot of smart pointers that you can use depending on your needs).

0
source

All Articles