I am aware that the C++ standard in its present form does not say
anything about threads, however I do have a relevant question.
I am working on Windows XP/VC++ 8.0.
Is there a problem new'ing a bunch of objects from one thread and
deleting them in another? I do something like:
struct GenericPointerD eleter
{
template<typena me T>
void operator()(T* p)
{
if (ptr != 0)
{
delete ptr;
ptr = 0;
}
}
};
typedef vector<classofp ointers*> vecptrs;
int main()
{
vecptrs myptrs;
CreateThread(.. .... (LPVOID)&myptrs ........);
// use some platform specific API to wait until
threadcallbackr outine terminates
pseudo_wait_for _terminate(thre adcallbackrouti ne);
for_each(myptrs .begin(), myptrs.end(), GenericPointerD eleter());
}
DWORD WINAPI threadcallbackr outine(LPVOID param)
{
vecptrs* my_ptrs = static_cast<vec ptrs*>(param);
my_ptrs->push_back(ne w classofpointers ());
return 0;
}
I have vastly simplified what is essentially happening in my
application...
Should I be careful about new'ing and deleting from the same thread?
May 10 '06
15 8231
In article <11************ **********@i40g 2000cwc.googleg roups.com>,
"Earl Purple" <ea********@gma il.com> wrote: Tamas Demjen wrote: Dilip wrote:
shared_ptr is probably the single most valuable part of Boost. It truly increases the stability of your code, not only by automatically cleaning up resources, but also by virtually eliminating accidental double deletions and dereferencing dead or uninitialized pointers. Using weak_ptr you can ensure that your weak references automatically expire when the last copy of the owned object they point to goes out of scope.
Would you know whether or not shared_ptr will be thread-safe?
So far, threading hasn't been introduced into the working draft. But
there is a significant effort to get multithreading issues into either
C++0X and/or a technical report. And a known issue is the thread safety
characteristics of shared_ptr.
All implementations of shared_ptr that I'm aware of currently make
shared_ptr as safe as a void*. You can concurrently manipulate two
copies of a shared_ptr, even if they manage the same underlying
reference. You may not concurrently manipulate a single shared_ptr.
And you may not concurrently manipulate a single pointee, even if
accessed via separate shared_ptrs. I.e. the reference count is thread
safe and nothing more.
This behavior is most likely that which will be adopted.
-Howard
Tamas Demjen wrote: I've written an introductory tutorial about shared_ptr, which should get you started:
http://tweakbits.com/articles/sharedptr/index.html
Here's a section from the tutorial with my comments inline:
What Is Wrong With The Standard Auto Pointer?
I dispute your title. auto_ptr is a simple pointer for simple needs. As
Stroustrup says, it "isn't a general smart pointer. However, it
provides the service for which it was designed -- exception safety for
automatic pointers -- with essentially no overhead" (_TC++PL_, 3rd ed.,
sec. 14.4.2). IOW, it is not "wrong"; it's just different. Indeed, the
Boost documentation for their smart pointers says, "These templates are
designed to complement [not replace] the std::auto_ptr template."
In fact, I find it very useful for communicating transfer of ownership
without involving shared_ptr when the latter would add ambiguity and
unnecessary overhead. Here are two common uses:
class A { /*...*/ };
std::auto_ptr<A > CreateA()
{
return std::auto_ptr<A >( new A );
}
class B
{
boost::scoped_p tr<A> a_;
public:
B( std::auto_ptr<A > a ) : a_( a ) {}
// ...
};
The CreateA() function signature makes clear (and tries to enforce!)
that the user is responsible for deleting that pointer that is
returned, and if you happen to want to use the object in a shared_ptr,
conveniently there is a shared_ptr constructor for just that purpose.
Hence, the following line would work fine while still using the minimal
(i.e. zero-overhead) tool for the job since other users may have
different needs:
boost::shared_p tr<A> pa( CreateA() );
In the case of class B, the use of auto_ptr makes clear that B is
assuming ownership of the A object passed to it. It could use
shared_ptr (but not scoped_ptr!), but that would be less clear if the
desired behavior of B is that it solely own that A instance. (I use
scoped_ptr as the member instead of another auto_ptr because the former
doesn't allow any copying, so the implicitly generated copy constructor
and assignment operator won't give me any hidden problems.)
The std::auto_ptr has a tremendous disadvantage: It can not be copied without destruction. When you need to make a copy of an auto pointer, the original instance is destroyed. This means you may only have a single copy of the object at any time.
First, this can be an advantage -- it just depends on the situation.
Second, the original instance is not "destroyed" (i.e. deleted).
Rather, the second instance of auto_ptr assumes ownership of the object
instance, and the first one no longer refers to it. Perhaps a better
word is "invalidate d."
This also means that auto_ptr can not be used with standard containers, such as vector, deque, list, set, and map. In fact, it can hardly be used in any class that relies on copy construction.
True, and that is also sometimes desirable. scoped_ptr fits the same
description, but it is also often useful.
Furthermore, auto_ptr is not safe, because nothing prevents you from doing a copy accidentally. And if you do so, you destroy the original copy.
True (if you replace "destroy the original copy" with "invalidate the
original auto_ptr"), but if you need to prevent accidental copying, you
should be using scoped_ptr. When the TR1/Boost smart pointers are
available, auto_ptr is most often used purely for *transferring*
ownership, not exception safety, ownership by a class, or copying
objects around. It could be better named, of course, as this bit of
history from the Boost docs relates:
"Greg Colvin proposed to the C++ Standards Committee classes named
auto_ptr and counted_ptr which were very similar to what we now call
scoped_ptr and shared_ptr. [Col-94] In one of the very few cases where
the Library Working Group's recommendations were not followed by the
full committee, counted_ptr was rejected and surprising
transfer-of-ownership semantics were added to auto_ptr."
As I've argued above, these transfer-of-ownership semantics are not
innately evil. They just must be used deliberately. When they aren't
desirable, a different smart pointer should be used instead.
Also, some less standard compliant C++ compilers let you store forward declared objects in an auto_ptr, and use that without ever including the full definition of the class. This always results in a memory leak.
No. First of all, it's okay to delete such a class if the destructor is
"trivial", and second, deleting a declared-but-undefined class instance
with a non-trivial destructor results in undefined behavior, which
could be but is not necessarily a memory leak. That is actually a
"problem" with the language, not just some compilers, and Boost uses an
"ingenious hack" (boost::checked _delete) to prevent the unintentional
deletion of a declared-but-not-defined class instance. It could be
added to auto_ptr, too, without breaking any existing, working code
(i.e. code that doesn't already result in undefined behavior), but I
don't know if that's in the plans.
Cheers! --M
Last time I tuned in to the conversation, the 'consensus' was that
thread safety is built into the reference counting scheme, whether you
need it or not! Boost's shared pointer uses a macro to globally enable
and disable thread safety. I argued vehemently that a defaulted
template paramater would be preferable for those of us who need
different shared pointer thread safety at different program points, but
alas... I still can't wrap my head around the rationale for it's
current incarnation.
This is based on an old conversation with Peter Dimov, so it may be out
of date, but my boost 1.32 system uses the macro approach.
--Jeremy Jurksztowicz
mlimber wrote:
Thanks for the feedback, I appreciate it. Also, some less standard compliant C++ compilers let you store forward declared objects in an auto_ptr, and use that without ever including the full definition of the class. This always results in a memory leak.
No. First of all, it's okay to delete such a class if the destructor is "trivial", and second, deleting a declared-but-undefined class instance with a non-trivial destructor results in undefined behavior, which could be but is not necessarily a memory leak. That is actually a "problem" with the language, not just some compilers, and Boost uses an "ingenious hack" (boost::checked _delete) to prevent the unintentional deletion of a declared-but-not-defined class instance.
I should probably rephrase my article and explain it better. Many
compilers show an error message in that case, but I know Borland
C++Builder doesn't. If you try to delete a forward declared object from
a template (such as auto_ptr), it's very well possible that you don't
get any warning or error. If that object happens to have a non-default
destructor, it's not going to be called:
// in .h
class ForwardDeclared ;
class Test
{
public:
Test();
private:
std::auto_ptr<F orwardDeclared> p;
};
// in .cpp:
#include "ForwardDeclare d.h"
Test::Test() : p(new ForwardDeclared ) { }
I know that this is a language issue, and I don't expect the compiler to
solve this problem. All I expect is a reliable error message. I agree,
checked_delete is an ingenious solution to ensure that an error message
is produced with every compiler. Since one of the compilers I use can't
produce an error message with auto_ptr, I don't feel safe using auto_ptr
as a member variable (at least not until my STL implementation adds
checked_delete into it).
Tom
Tamas Demjen wrote: mlimber wrote:
Thanks for the feedback, I appreciate it.
Also, some less standard compliant C++ compilers let you store forward declared objects in an auto_ptr, and use that without ever including the full definition of the class. This always results in a memory leak.
No. First of all, it's okay to delete such a class if the destructor is "trivial", and second, deleting a declared-but-undefined class instance with a non-trivial destructor results in undefined behavior, which could be but is not necessarily a memory leak. That is actually a "problem" with the language, not just some compilers, and Boost uses an "ingenious hack" (boost::checked _delete) to prevent the unintentional deletion of a declared-but-not-defined class instance.
I should probably rephrase my article and explain it better. Many compilers show an error message in that case, but I know Borland C++Builder doesn't.
Just curious: Is it an error or a warning?
If you try to delete a forward declared object from a template (such as auto_ptr), it's very well possible that you don't get any warning or error. If that object happens to have a non-default destructor, it's not going to be called:
To nitpick one more time: it's actually a "non-trivial" destructor not
a "non-default" one. The former is "Standardes e for saying that the
class, one or more of its direct bases, or one or more if its
non-static data members has a user-defined destructor" (B. Karlsson,
_Beyond the C++ Standard Library: An Introduction to Boost_, p. 84).
Deleting an incomplete type also result in undefined behavior if the
class in question overloads the delete operator. // in .h class ForwardDeclared ;
class Test { public: Test(); private: std::auto_ptr<F orwardDeclared> p; };
// in .cpp: #include "ForwardDeclare d.h"
Test::Test() : p(new ForwardDeclared ) { }
I know that this is a language issue, and I don't expect the compiler to solve this problem. All I expect is a reliable error message. I agree, checked_delete is an ingenious solution to ensure that an error message is produced with every compiler.
Boost's rationale for always using checked_delete in these
circumstances is that "Some compilers issue a warning when an
incomplete type is deleted, but unfortunately, not all do, and
programmers sometimes ignore or disable warnings."
Since one of the compilers I use can't produce an error message with auto_ptr, I don't feel safe using auto_ptr as a member variable (at least not until my STL implementation adds checked_delete into it).
As per my previous post, I agree that one should generally not use
auto_ptr as a class member; scoped_ptr is almost always the right
choice when one is tempted it use it as such.
Cheers! --M
mlimber wrote: Just curious: Is it an error or a warning?
Just verified it, it's a warning. In VC++ 2005, it's
warning C4150: deletion of pointer to incomplete type 'ForwardDeclare d';
no destructor called
To nitpick one more time: it's actually a "non-trivial" destructor not a "non-default" one. The former is "Standardes e for saying that the class, one or more of its direct bases, or one or more if its non-static data members has a user-defined destructor" (B. Karlsson, _Beyond the C++ Standard Library: An Introduction to Boost_, p. 84). Deleting an incomplete type also result in undefined behavior if the class in question overloads the delete operator.
Yes, that definition is a lot more precise. It's time to buy that book.
At the time I wrote my article, I wasn't able to find any practical
information about shared_ptr, so I decided to document my knowledge and
make it available to the others. You could say that the situation has
changed, and the book you mentioned is most likely more comprehensive
and exact than my little write-up.
Boost's rationale for always using checked_delete in these circumstances is that "Some compilers issue a warning when an incomplete type is deleted, but unfortunately, not all do, and programmers sometimes ignore or disable warnings."
That's exactly the case. A warning would be OK with me, but again, some
compilers are completely silent about it.
Tom This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Christopher Benson-Manica |
last post by:
Is the following code legal, moral, and advisable?
#include <iostream>
class A {
private:
int a;
public:
A() : a(42) {}
|
by: Raghu Rudra |
last post by:
I have an ASP.NET web application, which accepts posted xml to do its work
and returns response xml. This xml is large and is in the order of 1MB. I
started testing this web app with client utility which spawns multiple
threads to post xml to this web site. I noticed an interesting thing. When I
kept the client utility and the web app on the same machine (I know that
this is not ideal testing), the perf monitor showed me that number of max...
|
by: n2xssvv g02gfr12930 |
last post by:
In a job interview I was asked about the statement below:
delete this;
Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?
JB
|
by: peter.moss |
last post by:
I have an application that use log4net for operational logging. I
store some user data elsewhere and need to tie the two together. To
achieve this I pass the ThreadId across on the user table so I can see
what thread the user was running under and then look in the log4net
table to see what they were up to.
This works fine when I use AppDomain.GetCurrentThreadId() as the
ThreadIds match, but the compiler throws up an obsolete warning...
|
by: Xavier Décoret |
last post by:
Hi,
I long thought one could not delete a const pointer but the following
code compiles under g++ and visual net:
class Dummy
{
public:
Dummy() {}
~Dummy() {}
| |
by: ismail69 |
last post by:
I want to delete bunch of records from a table like,
delete from Table1 where col1 in (select col1 from Table2);
now col1 from Table2 will be some where b/w 200-500.
But Table1 will be having 3000-5000 records for a single entry from Table2.
Hence instead of deleting at a stretch, I want to get the col1 from Table2
in some Java datastructures...
|
by: Jean-Paul Calderone |
last post by:
On Sat, 23 Aug 2008 02:25:17 +0800, Leo Jay <python.leojay@gmail.comwrote:
No - it's just what I said. create_socket creates one socket and passes
it to read_socket and write_socket. read_socket calls connect on the
socket it is passed. write_socket calls accept on the socket it is passed.
So a single socket has connect and accept called on it. Now, main does
call create_socket twice, so this does happen to two sockets, but it's...
|
by: mac |
last post by:
hi all,
im creating a form wich wil upload images to a folder and
their names and other details to a database.
im able to do uploading but my delete function is not working, please
can anybody tell me mistake n help me??
image_uploader.php
<?
if(isset($_REQUEST))
{
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |