Skip to main content

Item 29: Avoid returning "handles" to internal data.

Item 29: Avoid returning "handles" to internal data.
A scene from an object-oriented romance:
Object A: Darling, don't ever change!
Object B: Don't worry, dear, I'm const.
Yet just as in real life, A wonders, "Can B be trusted?" And just as in real life, the answer often hinges on B's
nature: the constitution of its member functions.
Suppose B is a constant String object:
class String {
public:
String(const char *value);
~String();
//
//
//
//
operator char *() const;
see Item 11 for pos-
sible implementations;
see Item M5 for comments
on the first constructor
// convert String -> char*;
// see also Item M5
...
private:
char *data;
};
const String B("Hello World");
// B is a const object
Because B is const, it had better be the case that the value of B now and evermore is "Hello World". Of course,
this supposes that programmers working with B are playing the game in a civilized fashion. In particular, it
depends on the fact that nobody is "casting away the constness" of B through nefarious ploys such as this (see
Item 21):
String& alsoB =
const_cast(B);
// make alsoB another name
// for B, but without the
// constness
Given that no one is doing such evil deeds, however, it seems a safe bet that B will never change. Or does it?
Consider this sequence of events:
char *str = B;
strcpy(str, "Hi Mom");
// calls B.operator char*()
// modifies what str
// points to
Does B still have the value "Hello World", or has it suddenly mutated into something you might say to your
mother? The answer depends entirely on the implementation of String::operator char*.
Here's a careless implementation, one that does the wrong thing. However, it does it very efficiently, which is
why so many programmers fall into this trap:
// a fast, but incorrect implementation
inline String::operator char*() const
{ return data; }
The flaw in this function is that it's returning a "handle" ? in this case, a pointer ? to information that should be
hidden inside the String object on which the function is invoked. That handle gives callers unrestricted access to
what the private field data points to. In other words, after the statement
char *str = B;
the situation looks like this:
Clearly, any modification to the memory pointed to by str will also change the effective value of B. Thus, even
though B is declared const, and even though only const member functions are invoked on B, B might still acquire
different values as the program runs. In particular, if str modifies what it points to, B will also change.
There's nothing inherently wrong with the way String::operator char* is written. What's troublesome is that it can
be applied to constant objects. If the function weren't declared const, there would be no problem, because it
couldn't be applied to objects like B.
Yet it seems perfectly reasonable to turn a String object, even a constant one, into its equivalent char*, so you'd
like to keep this function const. If you want to do that, you must rewrite your implementation to avoid returning a
handle to the object's internal data:
// a slower, but safer implementation
inline String::operator char*() const
{
char *copy = new char[strlen(data) + 1];
strcpy(copy, data);
return copy;
}
This implementation is safe, because it returns a pointer to memory that contains a copy of the data to which the
String object points; there is no way to change the value of the String object through the pointer returned by this
function. As usual, such safety commands a price: this version of String::operator char* is slower than the
simple version above, and callers of this function must remember to use delete on the pointer that's returned.
If you think this version of operator char* is too slow, or if the potential memory leak makes you nervous (as
well it should), a slightly different tack is to return a pointer to constant chars:
class String {
public:
operator const char *() const;
...
};
inline String::operator const char*() const
{ return data; }
This function is fast and safe, and, though it's not the same as the function you originally specified, it suffices for
most applications. It's also the moral equivalent of the °C++ standardization committee's solution to the
string/char* conundrum: the standard string type contains a member function c_str that returns a const char*
version of the string in question. For more information on the standard string type, turn to Item 49.
A pointer isn't the only way to return a handle to internal data. References are just as easy to abuse. Here's a
common way to do it, again using the String class:
class String {
public:
...
char& operator[](int index) const
{ return data[index]; }
private:
char *data;
};
String s = "I'm not constant";
s[0] = 'x';
// fine, s isn't const
const String cs = "I'm constant";
cs[0] = 'x';
// this modifies the const
// string, but compilers
// won't notice
Notice how String::operator[] returns its result by reference. That means that the caller of this function gets
back another name for the internal element data[index], and that other name can be used to modify the internal
data of the supposedly constant object. This is the same problem you saw before, but this time the culprit is a
reference as a return value, not a pointer.
The general solutions to this kind of problem are the same as they were for pointers: either make the function
non-const, or rewrite it so that no handle is returned. For a solution to this particular problem ? how to write
String::operator[] so that it works for both const and non-const objects ? see Item 21.
const member functions aren't the only ones that need to worry about returning handles. Even non-const member
functions must reconcile themselves to the fact that the validity of a handle expires at the same time as the object
to which it corresponds. This may be sooner than a client expects, especially when the object in question is a
compiler-generated temporary object.
For example, take a look at this function, which returns a String object:
String someFamousAuthor()
{
switch (rand() % 3) {
case 0:
return "Margaret Mitchell";
case 1:
return "Stephen King";
case 2:
return "Scott Meyers";
}
return "";
}
// randomly chooses and
// returns an author's name
// rand() is in
// (and ? see
// Item 49)
// Wrote "Gone with the
// Wind," a true classic
// His stories have kept
// millions from sleeping
// at night
// Ahem, one of these
// things is not like the
// others...
// we can't get here, but
// all paths in a value-
// returning function must
// return a value, sigh
Kindly set aside your concerns about how "random" the values returned from rand are, and please humor my
delusions of grandeur in associating myself with real writers. Instead, focus on the fact that the return value of
someFamousAuthor is a String object, a temporary String object (see Item M19). Such objects are transient ?
their lifetimes generally extend only until the end of the expression containing the call to the function creating
them. In this case, that would be until the end of the expression containing the call to someFamousAuthor.
Now consider this use of someFamousAuthor, in which we assume that String declares an operator const char*
member function as described above:
const char *pc = someFamousAuthor();
cout << pc;
// uh oh...
Believe it or not, you can't predict what this code will do, at least not with any certainty. That's because by the
time you try to print out the sequence of characters pointed to by pc, that sequence is undefined. The difficulty
arises from the events that transpire during the initialization of pc:
1. A temporary String object is created to hold someFamousAuthor's return value.
2. That String is converted to a const char* via String's operator const char* member function, and pc is
initialized with the resulting pointer.
3. The temporary String object is destroyed, which means its destructor is called. Within the destructor, its
data pointer is deleted (the code is shown in Item 11). However, data points to the same memory as pc
does, so pc now points to deleted memory ? memory with undefined contents.
Because pc was initialized with a handle into a temporary object and temporary objects are destroyed shortly
after they're created, the handle became invalid before pc could do anything with it. For all intents and purposes,
pc was dead on arrival. Such is the danger of handles into temporary objects.
For const member functions, then, returning handles is ill-advised, because it violates abstraction. Even for
non-const member functions, however, returning handles can lead to trouble, especially when temporary objects
get involved. Handles can dangle, just like pointers, and just as you labor to avoid dangling pointers, you should
strive to avoid dangling handles, too.
Still, there's no reason to get fascist about it. It's not possible to stomp out all possible dangling pointers in
nontrivial programs, and it's rarely possible to eliminate all possible dangling handles, either. Nevertheless, if
you avoid returning handles when there's no compelling need, your programs will benefit, and so will your
reputation.

Comments

Popular posts from this blog

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checking a shared sec

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into /opt/course/1/context_default_no_kubectl.sh , but without the use of k

标 题: 关于Daniel Guo 律师

发信人: q123452017 (水天一色), 信区: I140 标  题: 关于Daniel Guo 律师 关键字: Daniel Guo 发信站: BBS 未名空间站 (Thu Apr 26 02:11:35 2018, 美东) 这些是lz根据亲身经历在 Immigration版上发的帖以及一些关于Daniel Guo 律师的回 帖,希望大家不要被一些马甲帖广告帖所骗,慎重考虑选择律师。 WG 和Guo两家律师对比 1. fully refund的合约上的区别 wegreened家是case不过只要第二次没有file就可以fully refund。郭家是要两次case 没过才给refund,而且只要第二次pl draft好律师就可以不退任何律师费。 2. 回信速度 wegreened家一般24小时内回信。郭律师是在可以快速回复的时候才回复很快,对于需 要时间回复或者是不愿意给出确切答复的时候就回复的比较慢。 比如:lz问过郭律师他们律所在nsc区域最近eb1a的通过率,大家也知道nsc现在杀手如 云,但是郭律师过了两天只回复说让秘书update最近的case然后去网页上查,但是上面 并没有写明tsc还是nsc。 lz还问过郭律师关于准备ps (他要求的文件)的一些问题,模版上有的东西不是很清 楚,但是他一般就是把模版上的东西再copy一遍发过来。 3. 材料区别 (推荐信) 因为我只收到郭律师写的推荐信,所以可以比下两家推荐信 wegreened家推荐信写的比较长,而且每封推荐信会用不同的语气和风格,会包含lz写 的research summary里面的某个方面 郭家四封推荐信都是一个格式,一种语气,连地址,信的称呼都是一样的,怎么看四封 推荐信都是同一个人写出来的。套路基本都是第一段目的,第二段介绍推荐人,第三段 某篇或几篇文章的abstract,最后结论 4. 前期材料准备 wegreened家要按照他们的模版准备一个十几页的research summary。 郭律师在签约之前说的是只需要准备五页左右的summary,但是在lz签完约收到推荐信 ,郭律师又发来一个很长的ps要lz自己填,而且和pl的格式基本差不多。 总结下来,申请自己上心最重要。但是如果选律师,lz更倾向于wegreened,