Can a pointer alternatively point to an empty or empty class?

Presumably not. Here is my use case:

I have two classes A and B.

class A { B *b_; }; class B { public: B(): b_string_("") {}; private: std::string b_string_; }; 

I want b_ to always point to object B. I want b_ to point to the "empty" object B instead of nullptr so that I can always dereference * b_ in a certain way to get an empty b_-> b_string. Therefore, I thought I would create a global "object of zero B": const B null_b . But I cannot (naturally) use this A ctor:

 A(): b_(&null_b) {}; 

since b_ cannot point to a constant variable. If not "null object B", b_ must point to mutable objects B.

Creating a global non-const solves the problem, but I want const protection, so I can guarantee that the "null object" never changes.

FWIW, this includes a large project where b_ points to a vector of B objects in another class. I could add an empty object B to this vector, but it amazes me like kludgy.

Is there a way or template to solve my problem?

+6
source share
3 answers

Instead of holding a pointer to object B , create a base class with virtual methods and pointers to the repository. Derive from it both class B and class Null_B , but do not allow modifications to methods on Null_B . Now, even if your Null_B object Null_B not const , it no longer matters.

As an added layer of protection, you can try to modify the Null_B object by Null_B exception so that you can detect and find a logical error.

+5
source

You cannot have a non const const pointer in a const object. And unfortunately, using const_cast to remove the const -ness of an object means that some code may later try to modify the object. (Note that undefined behavior is rejected by const if the source object is not constant, so technically the compiler is allowed to generate the generated code, which will fail if this happens. Unfortunately, in many cases this WILL NOT crash the object is something more complex than const char * or const int [] - allows the code to continue working after overwriting your object that you do not want to write).

However, since class B has a b_string_ member that is private, no external object can touch it, so you can make sure that any use of b_string_ is done through a virtual function (or several virtual functions), then derive another class from B , where and virtual function (s) says β€œSorry, you cannot do this” when the code tries to change the b_string in the derived object.

+3
source

Well, maybe that's not the case at all, but ... Could you use an instance of B instead of a pointer to B inside A? This would solve the potential dereferencing with noptp.

EDIT is good if B is too big, then you can create a lightweight shell around it and save an instance of that shell inside A. The wrapper will provide you with something meaningful if B is nullptr.

+1
source

Source: https://habr.com/ru/post/950846/


All Articles