C ++ Is creating objects dependent on others a good design?

I have a basic design that has three classes: a data class, a Holder class that contains and manages multiple Data objects, and a Wrapper returned by a holder that contains a reference to a Data object.

The problem is that the Wrapper shouldn't survive Holder, or it will contain a dangling link, since Holder is responsible for deleting Data objects. But since the Wrapper is designed to have a very short lifespan (get it in a function, do some calculations on its data, and let it go out of scope) this shouldn't be a problem, but I'm not sure if it's a good design.

Here are some solutions I was thinking:
-Almost for a user reading the documentation, technically the same thing happens with STL iterators
-Use shared_ptr to make sure the data lasts long enough, but it looks like brute force | -Make Wrapper will confirm that its holder is still there every time you use it.
-Any idea?

(I hope everyone understands this as English is not my first language)

Edit . If you want a less theoretical approach, it all comes from a little algorithm I'm trying to write for Sudokus's solution, Holder is the grid, data is the content of each window (result or temporal guess), and Wrapper is the Box class that contains a link to the data; and additional information such as row and column. I didn't say this initially because I want to know what to do in a more general situation.

+3


source to share


2 answers


Only returning a value Wrapper

can help ensure that the caller is not holding him out of the call area. Combined with a comment or documentation that "Wrappers are only valid for the life of the owner who created them" should suffice.

Either that, or you've decided that ownership Data

will not be transferred Wrapper

on creation Wrapper

, but Data

destroyed along with Wrapper

- but what if you want to destroy Wrapper

without deleting Data

? You will need a method to optionally relinquish ownership of Data

the Holder

.



Whichever you choose, you need to decide what belongs (i.e.: responsible for the lifetime) Data

and when - when you do, you can, if you like, use smart pointers to help with that control - but they won't make a design decision for you, and you can't just say "oh, I'll use smart pointers, not think about it."

Remember, if you can't manage smart pointers without heap, you don't have heap memory management with .

0


source


To clarify what you have already specified as parameters,



  • As you said, this shared_ptr<Data>

    is a good option. If performance isn't an issue, you should use it.

  • Never hold a pointer to Data

    in Wrapper

    . Store a descriptor that you can use to get a pointer to the corresponding object Data

    . Before being Data

    accessed through Wrapper

    , get a pointer to the object Data

    . If the pointer is invalid, enter exception

    . If the pointer is valid, follow the happy path.

0


source







All Articles