且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否总是邪恶有方法的结构?

更新时间:2023-11-10 18:54:58

对于有价值的,所有的标准STL函数都被定义为结构体,它们的唯一目的是具有成员函数; STL函数不应该有状态。



编辑:个人来说,每当一个类全部使用时,我使用 struct 公共成员。它不重要,只要一个是一致的。


I've just been browsing and spotted the following...

When should you use a class vs a struct in C++?

The consensus there is that, by convention, you should only use struct for POD, no methods, etc.

I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions as members. The struct should still be POD by most of the usual rules - in particular it must be safe to copy using memcpy. It must have all member data public. But it still makes sense to me to have helper functions as members. I wouldn't even necessarily object to a private method, though I don't recall ever doing this myself. And although it breaks the normal POD rules, I wouldn't object to a struct having constructors, provided they were just initialise-a-few-fields constructors (overriding assignment or destructors would definitely be against the rules).

To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction. The logical place to put the helper functions for your collection-of-fields may well be within the struct.

I even think I once read some advice along these lines, though I don't remember where.

Is this against accepted best practice?

EDIT - POD (Plain Old Data) is misrepresented by this question. In particular, a struct can be non-POD purely because a member is non-POD - e.g. an aggregate with a member of type std::string. That aggregate must not be copied with memcpy. In case of confusion, see here.

For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.

EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.