C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Suggestion: non-static member variables for static-duration-only classes

From: Walt Karas <wkaras_at_[hidden]>
Date: Sat, 4 Oct 2025 03:45:52 +0000 (UTC)
On Friday, October 3, 2025 at 09:15:42 PM EDT, Thiago Macieira <thiago_at_[hidden]> wrote:





On Friday, 3 October 2025 10:25:57 Pacific Daylight Time Walt Karas wrote:
> You can already do this by having a static thread_local member or non-member
> that is your data. It's a bit more typing, but I don't see this as a
> frequent enough need to require direct language support.
>
> Response: I don't understand what you mean by "that is your data".


struct MyClassData;
class MyClass
{
// methods go here
private:
static thread_local MyClassData d;
};

Then just have your functions use d.something;

Response: Sorry, I still don't understand. Can you show me how you would rework this code?

#include <thread>
#include <atomic>
#include <mutex>
#include <set>


class [[program_lifetime]] Counter
{
public:
void incr() { ++pt.count; }
unsigned collect()
{
unsigned sum{0};
{
std::lock_guard lg{mtx};
for (auto &pt_ : pt_active)
sum += pt_->count.exchange(0);
}
if (sum)
total.fetch_add(sum);
return sum;
}
private:
std::atomic<unsigned> total{0}, num_threads{0};
struct Per_thread
{
std::atomic<unsigned> count{0};
Counter &parent;
Per_thread(Counter &c) : parent{c}
{
std::lock_guard lg{parent.mtx};
parent.pt_active.insert(this);
}
~Per_thread()
{
{
std::lock_guard lg{parent.mtx};
parent.pt_active.erase(this);
}
if (count)
parent.total.fetch_add(count);
--parent.num_threads;
}
};
thread_local Per_thread pt{*this};
std::mutex mtx;
std::set<Per_thread *> pt_active;
};


Counter tcp_packets, udp_packets;

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Principal Engineer - Intel Data Center Group

Received on 2025-10-04 03:49:19