-1

I have a pointer which sliced, but I don't exactly know where and why. There are two lines of code which I think could lead to splicing:

The creation of a unique pointer:

map.insert(make_pair("ChildA", unique_ptr<Base>(new ChildA())));

and the returning of raw pointer from my unique pointer:

return map["ChildA"].get();

note that:

  • Class ChildA inherits Base
  • Base has a virtual destructor
  • the map in the example above is of type:

    map<string, unique_ptr<Base> >
    

Does splicing occur in either of the lines of code stated above? Is there an easy way to avoid where it does?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Yaxlat
  • 665
  • 1
  • 10
  • 25
  • 1
    You meant `return map["ChildA"].get()` right ? – WhozCraig Oct 07 '14 at 07:05
  • 1
    `return map[ChildA].get()` is not valid code - always [post REAL code](http://stackoverflow.com/help/mcve). – Angew is no longer proud of SO Oct 07 '14 at 07:05
  • 2
    IIRC, slicing only occurs on copies of value objects; so not references, and not pointers (even when in a smart pointer). So this would depend on what the type is in signature of the function that contains `return map[ChildA].get();`. What is the signature and how is the result used? – Niall Oct 07 '14 at 07:05
  • How do you know it is sliced? Why haven't you posted the relative errors? Please include an [mvce](http://stackoverflow.com/help/mcve) instead of bits of code where you think the problem is. – user657267 Oct 07 '14 at 07:06
  • If you did something like `Base foo() { return *(map["ChildA"].get()); }`, yes that would both slice and be simultaneously utterly hideous. Now post your *real* code. – WhozCraig Oct 07 '14 at 07:07
  • There is no slicing in the code you've shown (after the substituion of `["ChildA"]` for `[ChildA]` to make it valid). Pointers can't slice. – Angew is no longer proud of SO Oct 07 '14 at 07:07
  • It is not really the same, but maybe [this](http://stackoverflow.com/q/26097428/3062311) will also help you a little. I had a copy ctor and then I have changed it to move ctor and then I just gave up, because I really need a copy ctor, and unique_ptr are not copyable. – sop Oct 07 '14 at 07:36
  • @WhozCraig sorry that was a typo. I edited the question – Yaxlat Oct 07 '14 at 07:46

1 Answers1

0

There is no slicing taking place in the code you've posted as far as I can see.

Demo: http://ideone.com/8InZ6H

Slicing will occur if you try to copy a Child1 into a Base by value. Are you sure you're not doing that anywhere else in your code?

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82