std::vector, default construction, C++11 and breaking changes

前端 未结 2 2102
南笙
南笙 2020-11-27 16:41

I ran today against a quite subtle issue I\'d like to have your opinion on.

Consider the following garden-variety shared-body-idiom class:

struct S
{         


        
2条回答
  •  甜味超标
    2020-11-27 17:14

    I think solution for use-case you described is not optimal and not complete, that's why you got problems upgrading to C++11.

    C++ always cares about semantic and when you write program in c++ you'd better to understand your semantic. So in your case you wish to create N objects, but while you are not changing them you wish them to share same memory for optimization. Nice idea, but how to get this done: 1) copy constructor. 2) static implementation + copy constructor. Have you considered both solutions?

    Consider you need M vectors of N objects, how many times shared memory will be allocated if you choose 1st scenario? It is M, but why do we need to allocate memory M times if we want to create vectors containing MxN objects?

    So correct implementation here is to point to static memory by default, and allocate memory only if object is changed. In such a case allocating M vectors of N objects will give you... 1 'shared' memory allocation.

    In your case you violated correct semantic abusing copy constructor, which is: 1) not obvious 2) not optimal and now you have to pay off.

提交回复
热议问题