can I do "delete &reference"

C

CodeCracker

class A {
public:
A(obj &objRef): mObj(objRef) {
}
~A() {
delete &mObj;
}
private:
Obj &mObj;
}

Can I do what I did in ~A() ?
 
D

Donovan Rebbechi

class A {
public:
A(obj &objRef): mObj(objRef) {
}
~A() {
delete &mObj;
}
private:
Obj &mObj;
}

Can I do what I did in ~A() ?

Yes, but you probably shouldn't

cheers,
 
M

Minti

CodeCracker said:
class A {
public:
A(obj &objRef): mObj(objRef) {
}
~A() {
delete &mObj;
}
private:
Obj &mObj;
}

Can I do what I did in ~A() ?

Can you make sure that your object has been allocated on heap rather
than on stack?
 
P

Phlip

Minti said:
CodeCracker wrote:
Can you make sure that your object has been allocated on heap rather
than on stack?

You also can't tell if a pointer points to an object on the heap or stack.

From the top: Prefer weaker constructions over constructions with wider
interfaces. Prefer int unless you need double, prefer std::string unless you
need the freedom of char[], and prefer references unless you need one of
these:

1. reseat to something else
2. index with [] (essentially the same as 1)
3. could be NULL
4. a compilable comment

Despite item 3, you should not pass NULL into object interfaces (you should
pass handles to Null Object pattern objects, at least). Items 1 and 2 imply
a method should not take a pointer argument and point it to something else
as a convenience.

Item 4 is the clicker. An interface should request a pointer (or better yet,
a smart pointer) if it documents that it will own the pointee, and will
delete it. Passing such a pointer symbolizes transfer of ownership.

Without item 4, the other items indicate you should pass a reference even if
you intend to delete the referand from the heap. So, like the others said,
don't.

Now research smart pointers, to learn to encapsulate the ownership from the
clients of a heap object.
 
R

Ron Natalie

Minti said:
Can you make sure that your object has been allocated on heap rather
than on stack?

Even that isn't good enough. mObj is NOT allocated with new,
it's undefined behavior to free it with delete.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,203
Messages
2,571,059
Members
47,668
Latest member
SamiraShac

Latest Threads

Top