There's two questions hidden in here. The first one is:
Var *p = new Var("name", 1);
But I have to clear the variable pointed to by p with delete p later
on in the program.
I want to declare a stack variable so it is automatically cleared
after function exits
So here, you're asking how to allocate memory without having to explicitly clean it up afterwards. The solution is to use std::unique_ptr
:
std::unique_ptr<Var> p(new Var("name", 1));
Voila! unique_ptr will automatically clean itself up, it has virtually no overhead compared to a raw pointer, and it's overloaded the * and -> operators so you can use it just like a raw pointer. Search for "C++11 smart pointers" if you want to know more.
The second question is:
I only want to get the pointer, and the following:
Var v("name", 1);
Var *p = &v;
is quite tedious, and specifier v will never be referenced.
The important point here is that Var *p = &v
is completely unnecessary. If you have a function that requires a pointer, you can use &v
on the spot:
void SomeFunc(const Var* p);
// ...
Var v("name", 1);
SomeFunc(&v);
There's no need to put &v in a separate variable before passing it into a function that requires a pointer.
The exception is if the function takes a reference to a pointer (or a pointer to a pointer):
void SomeFunc2(Var*& p);
void SomeFunc3(Var** p);
These types of functions are rare in modern C++, and when you see them, you should read the documentation for that function very carefully. More often than not, those functions will allocate memory, and you'll have to free it explicitly with some other function.