Home > front end >  Raw pointer but modern way
Raw pointer but modern way

Time:02-03

I have to have a semantic stack in my project which is going to hold multiple types in it.
I aim to have my project to use modern C .
What is the correct way to have a stack of any type ?
Equivalent version in java is Stack<Object>.
Which of these are correct?

  1. Use void* and cast it to the type I want.
  2. Something as 1 but using some smart pointers. (I don't know what)

CodePudding user response:

  1. std::any is for storing objects of any type (limitations may apply).

However, the entire design of storing any type is rarely ideal. Often, it's better to use variadic templates to keep polymorphism entirely compile time, or to have only a limited set of types (std::variant), or even to use an OOP hierarchy. Which is more appropriate depends on the use case.

CodePudding user response:

void* pointers is a pure C stuff that is obsolete in C . You can use use smart pointers (such as unique_ptr or shared_ptr) when you dynamically allocate memory for your objects/variables/members. Do not wrap some API pointer objects that is not created by you in smart pointer objects. When you pass arguments into a function and you need to avoid copying of objects you better use references instead of pointers. However, you can use raw pointers in C but this is not recommended.

  •  Tags:  
  • Related