473,394 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to check if a weak_ptr is empty?

It seems useful to be able to distinguish between an empty weak_ptr and
one that has merely expired. For example:

void f(weak_ptr<T> wp)
{
if (/* wp is empty */)
{
// Act is if a NULL pointer was passed.
}
else
{
// Obtain a shared_ptr. Throw an exception if wp has expired.
shared_ptr<T> sp(wp) ;
}
}

There seems to be no way, however, to test a weak_ptr for emptiness. Is
this an oversight in the design, or a deliberate design decision?

--
Alan Johnson
May 21 '06 #1
7 15873
Alan Johnson wrote:
It seems useful to be able to distinguish between an empty weak_ptr and
one that has merely expired. For example:
Note that A> Boost questions will work best on the Boost mailing list, and
that B> you could pass a pointer to a NullObject and take out the if, and C>
you should typedef all template instances, including private ones like
weak_ptr<T>.

That said...
void f(weak_ptr<T> wp)
{
if (/* wp is empty */)
if (wp.get() == NULL) ? If not, then:

if (wp.operator->() == NULL)
There seems to be no way, however, to test a weak_ptr for emptiness. Is
this an oversight in the design, or a deliberate design decision?


And if the design intends to prevent this test, then maybe my suggestions
won't work, for some obscure reason.

Posting to the Boost mailing list will decrease the odds that posts like
mine will get reviewed and possibly corrected.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 21 '06 #2
Alan Johnson wrote:
It seems useful to be able to distinguish between an empty weak_ptr and
one that has merely expired. For example:

void f(weak_ptr<T> wp)
{
if (/* wp is empty */)
{
// Act is if a NULL pointer was passed.
}
else
{
// Obtain a shared_ptr. Throw an exception if wp has expired.
shared_ptr<T> sp(wp) ;
}
}


This code doesn't illustrate why this distinction is useful. A more
idiomatic way to write it would be:

shared_ptr<T> sp(wp);
if (!sp)
// Act as if a null pointer was passed

Constructing a shared_ptr object from a weak_ptr object is not an
expensive operation. I don't see any good reason to try to avoid it.

But if for some reason you don't want to do that, you can check
wp.use_count() == 0.

--

Pete Becker
Roundhouse Consulting, Ltd.
May 21 '06 #3
Phlip wrote:

Note that A> Boost questions will work best on the Boost mailing list, and


On the other hand, questions about TR1 and about standard C++ work best
here. shared_ptr and weak_ptr are in TR1 and, as of last month, in the
next version of the C++ standard.

--

Pete Becker
Roundhouse Consulting, Ltd.
May 21 '06 #4
Pete Becker wrote:
Alan Johnson wrote:
It seems useful to be able to distinguish between an empty weak_ptr
and one that has merely expired. For example:

void f(weak_ptr<T> wp)
{
if (/* wp is empty */)
{
// Act is if a NULL pointer was passed.
}
else
{
// Obtain a shared_ptr. Throw an exception if wp has expired.
shared_ptr<T> sp(wp) ;
}
}


This code doesn't illustrate why this distinction is useful. A more
idiomatic way to write it would be:

shared_ptr<T> sp(wp);
if (!sp)
// Act as if a null pointer was passed


Consider the non-smart-pointer version of a function:

void f(T *p)
{
if (p)
{
// Case 1: Do one thing.
// Case 2: Undefined behavior because p isn't valid.
}
else
{
// Case 3: Do another thing.
}
}

The obvious solution to avoiding Case 2 above is to simply not pass an
invalid pointer. But that isn't always easy. Consider this motivating
example. You have a server that allows multiple users to connect.
While connected, they may schedule events to occur at some time in the
future. Your "event" objects store a pointer to the user that scheduled
them. What should you do, though, if a user schedules an event to be
processed 30 minutes from now, and then immediately disconnects?

A lot of solutions come to mind, but a particularly simple one is to
have your events store a weak_ptr to the scheduling user, and then find
out about invalid users in Case 2. (Yes, in this contrived example you
could distinguish Case 2 from Case 3 prior to calling f, but that isn't
the point.)

The question is how to distinguish "a weak_ptr to nothing" (Case 3) from
"a weak_ptr to something invalid" (Case 2).

Constructing a shared_ptr won't work. Consider the following fragment,
in which BOTH constructions of a shared pointer will throw bad_weak_ptr.

weak_ptr<T> wp1, wp2, wp3 ;

{
shared_ptr<T> temp_sp(new T) ;
wp1 = temp_sp ;
wp2 = temp_sp ;

// Case 1: wp1 is a valid weak_ptr
share_ptr<T> sp1(wp1) ;
}

// Case 2: wp2 is an invalid weak_ptr
shared_ptr<T> sp2(wp2) ;

// Case 3: wp3 is a valid weak_ptr, but pointing to nothing.
shared_ptr<T> sp3(wp3) ;
The use_count() member is equally problematic, as it returns 0 for both
an invalid weak_ptr and a weak_ptr to nothing. Likewise, lock() will
return an empty shared_ptr in both cases. The only way I've found that
does seem to work is something like:

bool is_empty(weak_ptr<T> wp)
{
weak_ptr<T> empty ;

// operator < claims to establish a strict weak order, so this
// should always work.
return (!(wp < empty) && !(empty < wp)) ;
}
It is my opinion that throwing bad_weak_ptr when constructing a
shared_ptr from an empty weak_ptr is a design flaw. The "proper" thing
to do would be to construct an empty shared_ptr.

--
Alan Johnson
May 21 '06 #5
Alan Johnson wrote:
It is my opinion that throwing bad_weak_ptr when constructing a
shared_ptr from an empty weak_ptr is a design flaw. The "proper" thing
to do would be to construct an empty shared_ptr.


Actually, to be technical, I think this is a symptom of the problem.
The latest tr1 smart pointer proposal I can find is:
<url: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1450.html>

It says that shared_ptr's weak_ptr constructor throws bad_weak_ptr when
the weak_ptr has expired, which is as it should be.

It also says that weak_ptr's expired() returns "use_count() == 0". This
is the problem. If the weak_ptr is empty, expired() should ALWAYS
return false. It is impossible for an pointer to nothing to expire.

With that change, the "more idiomatic way" that you suggest would work
as expected.

--
Alan Johnson
May 21 '06 #6
Pete Becker wrote:
Note that A> Boost questions will work best on the Boost mailing list,
and
On the other hand, questions about TR1 and about standard C++ work best
here. shared_ptr and weak_ptr are in TR1 and, as of last month, in the
next version of the C++ standard.


Were my other answers the best possible?

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 21 '06 #7
Phlip wrote:

Were my other answers the best possible?


I'm not familiar with Boost's version of shared_ptr and weak_ptr. In TR1
and the standard, weak_ptr doesn't have member functions get() and
operator->(), so you can't use them to figure out whether a weak_ptr
object is empty. The only information you can get directly from a
weak_ptr object is its use count and whether it's expired. For anything
else, you have to copy it into a shared_ptr object.

--

Pete Becker
Roundhouse Consulting, Ltd.

May 21 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: KathyB | last post by:
Hi, I'm trying to find a way to validate input text boxes where I don't know the names until the page is rendered. I've got 2 validate functions that fire with the onsubmit button of a "mini" form...
2
by: Paul Telco | last post by:
Hello, I'm a new user designing a simple database to retrieve pre-prepared docunents for printing. I have five tables, a form to design the documents, a form to customise and retrieve the...
30
by: S. van Beek | last post by:
Dear reader A record set can be empty because the condition in the query delivers no records. Is there a VBA code to check the status of a record set, record set empty
1
by: Oleg Ogurok | last post by:
Hi all, I want to use RegularExpressionValidator to enforce non-empty integer format in a TextBox. However, the validator doesn't give the error when the textbox is empty. For example, if...
4
by: Sosh123 | last post by:
Hi, Could anybody suggest a way of checking for an empty datareader, without using Read()? Thanks
4
by: whisher | last post by:
Hi. I'm taking my first steps on regex I set up this simple function to check if a form field is empty or with only space. var onlySpaceRegexp = /^\s*$/; function isEmpty(val) { if...
7
by: lphang | last post by:
I am reading a simple text file that will contains three set of string values as follow: "1234567", "ABC123456", "" I have my codes as follow trying to check for an empty string, with the input...
3
by: akshalika | last post by:
I want regular expression which check for empty. pls help me.
10
by: klharding | last post by:
I am reading the contents of a text file into variables. All works well if the text file does not exist, or it does exist and contains 4 rows of data. But I need to account for rows being empty or...
3
by: robin27th | last post by:
Hi, I am very new to access. I am asking something basic. Private Sub Command12_Click() Dim strAbc As String strAbc = "a" MsgBox IsNull(strAbc) MsgBox IsEmpty(strAbc) End Sub
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.