Pointer question

So in my code, i want to create a pointer to some data by doing the following:

1
2
3

Something *A = &Something(parameter1, parameter2);


So, i'm passing in 2 parameters into "Something", to create a "Something" pointer. Is this the correct way of doing this? I don't particularly want to use new, as i don't want copies of the data.
Or is it better to do:

1
2
3
4

Something *A;
*A = Something(parameter1, parameter2);
No, the correct way to create a Something* is
 
Something* A = new Something(parameters);


What you wrote will maybe compile, but you'd be in pretty deep trouble if you actually were to use these pointers, cause they would point to invalid data.
Last edited on
Hi

So in my code, i want to create a pointer to some data by doing the following:


What do you mean by 'data'?

Something(parameter1, parameter2);

That looks like you're creating an object of class Something. Why would you want to get a pointer to it? Objects in C++ are usually passed around by reference - it's much cleaner and safer.



keineahnung - there's no way around dynamic allocation if you need dynamic data though.
Both don't make sense. The latter will crash additionally.

A pointer to a local variable is dangerous. Why not using 'Something' directly?
Hi @hanst99

keineahnung - there's no way around dynamic allocation if you need dynamic data though.


Of course you're right but I'm a wimp - if new isn't wrapped up in a shared_ptr I run away ;)
I find myself guilty of not using smart pointers where it would have been appropriate.
Topic archived. No new replies allowed.