Question

Does this delete all the pointers or does this just delete the first pointer p1?

delete p1,p2,p3,p4,p5;  
Était-ce utile?

La solution

It is equivalent to:

(((((delete p1),p2),p3),p4),p5);

That is, it deletes p1 and then the comma operator is applied to the result (of which there is none) and p2. The expressions p2 to p5 are simply evaluated and the results discarded.

Autres conseils

Because ',' is comma operator obviously only the first object pointed to gets deleted, while the rest of expressions is evaluated and the results are discarded:

class A{
  public:
    string name_;

    A(){}
    A(string name):name_(name){}
    ~A(){cout<<"~A"<<name_;}
};

int main(){
    A* a1=new A("a1");
    A* a2=new A("a2");
    delete a1, a2;
    cout<<"\n.....\n";
    delete a2, a1;
//...

output:

~Aa1

....

~Aa2

It deletes the first one.

The comma operator evaluates what's in front of the comma then discards it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top