c++ - Unique id of class instance -


i have class this:

class exampleclass {  private:     int _id;     string _data;  public:     exampleclass(const string &str) {         _data = str;     }     ~exampleclass() {      }     //and on...      } 

how can add unique(!) integer identifier (_id) every instance of class without using global variable?

use private static member int, shared among instance of class. in static int in constructor increment it, , save it's value id member;

class exampleclass {  private:     int _id;     string _data;     static int counter=0; public:     exampleclass(const string &str) {         _data = str;          id=++counter;     } 

update:

you need take consideration in copy constructor , operator= behavior want (depends on needs, new object or identical one).


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -