Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Is using Shared_ptr bad practice(C++)?

+1 vote
asked Dec 21, 2021 by Areeb Sherjil (1,960 points)
if you have a class that has pointers, is it okay that it can take in pointers and replace it's member ones from the argument of constructor?

class PowerComputation
{
public:
PowerComputation(std::shared_ptr<Numerator>num, std::shared_ptr<Denom>denom);// take in pointers
friend std::ostream& operator<<(std::ostream& output, const PowerComputation&);
private:
std::shared_ptr<Numerator>num=nullptr;
std::shared_ptr<Denom>denom=nullptr;
};

is this okay or does it look like bad practice?

PowerComputation::PowerComputation(std::shared_ptr<Numerator>num, std::shared_ptr<Denom>denom)
{
this->num = num;
this->denom = denom;
}

shared pointer is used since two pointers are pointing to the same memory location

Full code :

https://onlinegdb.com/F-7_Rs4up

1 Answer

0 votes
answered Dec 27, 2021 by Peter Minarik (87,340 points)
selected Jan 1, 2022 by Areeb Sherjil
 
Best answer

It is encouraged to use shared pointers to have a garbage-collection like facility.

Please, read more about shared pointers here.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...