简体   繁体   中英

Apparent encapsulation

The new command allocates memory in the heap to store an object. Static allocation may cause the object to be put on the stack instead. But they're both not protected area of memory. I can access to this, which is just the address of the object, and then use the indirection operator, so pointing to the object fields:

string str=string("hello");
void** str_this=(void**)&str;
char* str_data= (char*)*str_this;
str_data[0]='s';
str_data[1]=0;
cout <<str_data; // prints "sello"

So is this still considered encapsulation? Is charge of the class user (who instantiates the object) to avoid poiting to it's data?

Encapsulation in programming does not usually mean "impossible to work around if you really really try".

It usually means closer to "being able to make a clear distinction what is supposed to be exposed or not and not have things accidentally exposed or used".

I don't think anyone will mistake your code for accessing a string the way it's supposed to be accessed.

C++ is a powerful language. With great power comes great responsibility, as a comic book superhero once said.

Once you cast an object pointer to void* and then recast that pointer to another type, in this case char* , you have entered into the land of undefined behavior . The language makes no guarantees about what will and what will not work if you try to use that char* pointer. It is only legal to recast the void* back to the original type ( string* ).

Invoking undefined behavior is not a legitimate way of breaking encapsulation, because once you cross that undefined behavior threshold, anything is possible (just not portable).

Your code implicitly relies on a particular implementation of std::string. In other words, your code is breaking the encapsulation of std::string. Worse yet, it invokes undefined behavior, so it may work, or it may not, or it may crash...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM