Reputation: 10156
To avoid keep having to use ->
and instead work directly with the object, is it acceptable practice to do:
obj x = *(new obj(...));
...
delete &obj;
Upvotes: 16
Views: 4034
Reputation: 254631
Certainly not; that copies the dynamic object to an automatic variable, loses the only pointer to it, and then attempts to delete the automatic copy. You've got a memory leak and an invalid deletion.
Much better would be to use an automatic variable in the first place:
obj x(...);
...
// no need to delete anything
or, if it really must be dynamic for some reason (because it's too big for the stack, or you don't always want to destroy it here), then use a smart pointer, and a reference if you really don't like ->
std::unique_ptr<obj> p(new obj(...));
obj & x = *p;
...
// still no need to delete anything
Changing your x
into a reference would be valid (as long as you're careful that exceptions, early function returns, etc. won't cause a leak), but would cause howls of confusion among anyone unfortunate enough to have to maintain it.
Upvotes: 7
Reputation: 24956
You cannot delete your object properly if you do it like that.
Implicitly you do the following.
class A
{
public:
int test (void) { return 1; }
};
int main (void)
{
A * p = new A;
A v(*p);
//...
delete &v; // &v != p and v is not constructed via new!
return 0;
}
If you want to work with an object-like-syntax you can bind a reference to the object.
class A
{
public:
int test (void) { return 1; }
};
int main (void)
{
A * p = new A;
A & r = *p;
int i = r.test();
delete p;
return 0;
}
If you delete your object through the same pointer, there will be no leak.
Upvotes: 0
Reputation: 126512
This is not just poor practice, but:
obj
will store a copy of the original object created by the new
expression, and the pointer to that object returned by new
is lost;delete
a pointer to an object that was not allocated with new
. Per paragraph 5.3.5/2 of the C++11 Standard:[...] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.
Upvotes: 31
Reputation: 258618
No, and in fact this leads to a leak. x
is copy initialized, so the original object pointed to by new obj
is lost.
Just use
obj x(...);
No need for dynamic allocation. Or
obj x = obj(...);
if you must (doubt it).
Upvotes: 9