Is targeting a viable technique?

Suppose I have a class called AudioSample, the implementation is not relevant. AudioSamples can be downloaded from several sources, for each source I get a class from AudioSample, which adds the appropriate loader code for this source. After loading, I slice the object on purpose, passing it to a function that uses AudioSampleby value.

It seems to me that this prevents the base class from becoming contaminated by various loading functions and prevents me from modifying the (tested and verified) base class when adding a new bootloader.

However, when I search for stackoverflow to trim objects, I find answers that describe this as a problem and explain it with potential traps, and this makes me wonder: am I using it the way I shouldn't? Will I encounter potential problems doing this I do not currently know?

+6
source share
3 answers

, . , "WTF", . - WTF , , , : ", , ".

, . - :

class AudioSampleLoadedViaFoo : public AudioSample
{
  // ...
public:
  AudioSample getLoadedSample() const
  {
    return *this; // Slice on purpose to remove load-specific stuff
  }
};

, , - .

+6

AudioSample,

, " " , / , factory " " std::function.

slicing , , , , ( ) . ?

, , , std::string , ?

+3

How do you know which bootloader code to call? If an object is sliced, one of the things that is sliced ​​is polymorphic behavior - everything behaves like an instance of a base class. And since it is so easy to prevent (pass by reference or pointer, which in any case is probably more efficient in terms of copies made), it is difficult to understand why you will ever want to do this.

0
source

Source: https://habr.com/ru/post/1015877/


All Articles