O
O
olava002021-08-19 16:26:23
C++ / C#
olava00, 2021-08-19 16:26:23

Class initialization?

class test_t
{
public:
void test();
std::string test_2();
};

int main()
{
test_t test_1;
test_t test_2 = { };
test_t* test_3 = new test_t();
}


which method is more optimal?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-08-19
@olava00

In your example, there are classes without data at all, so there is no difference between the first and second options. The third will allocate memory for the object not on the stack, but on the heap - therefore, the allocation and work with the object will usually take longer.
If there were data in the object , then the first option would be the fastest, because it would not initialize anything, unlike the others.
If the object also had a constructor , then the first and second variants would be identical.
The third option always initializes the object and allocates memory, so it will be slower.

C
cunion, 2021-08-19
@0hquazEd

Usually, the first initialization method is always used. The third is pointer initialization and has nothing to do with the other two.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question