Feb 28, 2018 at 12:53pm UTC
In Java and other languages it is much easier to create a new object for a function, such as:
doSomething(new Object(1, 2, 3, 4));
In C++, the equivalent for a function that doesn't take a pointer as a parameter would be:
doSomething(*(new Object(1, 2, 3, 4)));
Is this a bad practice?
Last edited on Feb 28, 2018 at 12:54pm UTC
Feb 28, 2018 at 1:10pm UTC
In Java all the stuff created by new will be garbage collected.
In C++ you have to delete it yourself.
Much better practice is to use a smart pointer or pass it by value.
Feb 28, 2018 at 1:10pm UTC
the equivalent would be doSomething(Object(1,2,3,4));
doSomething(*(new Object(1, 2, 3, 4)));
is leaking memory
Feb 28, 2018 at 1:15pm UTC
As ne555 says, in C++ the equivalent is to NOT USE NEW.
I see this a lot in people coming from Java; they default to creating everything on the heap, using new. In C++, you should avoid it. Use it only when you HAVE to. Not just because you can.
Feb 28, 2018 at 1:58pm UTC
And, for the cases when you actually need to work with raw pointers (rare in C++11), you would pass the pointer without dereferencing it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
struct Node {
Node() : data(0), next(nullptr ) {}
Node(int data) : data(data), next(nullptr ) {}
int data;
Node* next;
};
struct DataStructure {
DataStructure()
{
node = new Node;
node->data = 0;
node->next = nullptr ;
}
~DataStructure()
{
delete node;
if (node->next)
{
delete node->next;
}
}
void setNext(Node* node)
{
node->next = node;
}
Node* node;
};
int main()
{
DataStructure ds;
ds.setNext(new Node(42));
}
Last edited on Feb 28, 2018 at 2:55pm UTC
Feb 28, 2018 at 3:44pm UTC
Thank you all for the answers!