473,769 Members | 8,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Smart pointers: Conditional initialization

Hi,

I'm having a hard time figuring out how I can initialize a smart pointer
based on a certain condition:

if something then
ptr = 0; // init with NULL
else
ptr = new XYZ; // init with a sane value
endif

I know assignment doesn't work for a smart pointer unless the assigned
value is a smart pointer itself.

Any ideas how I can trick the compiler to do what I need? The problem is
simply that smart pointers expect the pointee to be passed to their
ctor, but the ctor is only called once.

Regards,
Matthias Kaeppler
Nov 26 '05 #1
4 2853
* Matthias Kaeppler:

I'm having a hard time figuring out how I can initialize a smart pointer
based on a certain condition:

if something then
ptr = 0; // init with NULL
else
ptr = new XYZ; // init with a sane value
endif


If this a "next"-pointer in a linked list, or some such, then maybe.

Otherwise having a potential nullpointer around only leads to problems.

But it's simple to shoot yourself in the foot, if you so want:

SmartPtr ptr( condition? new XYZ : 0 );
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 26 '05 #2
Matthias Kaeppler wrote:
Hi,

I'm having a hard time figuring out how I can initialize a smart pointer
based on a certain condition:

if something then
ptr = 0; // init with NULL
else
ptr = new XYZ; // init with a sane value
endif

I know assignment doesn't work for a smart pointer unless the assigned
value is a smart pointer itself.

Any ideas how I can trick the compiler to do what I need? The problem is
simply that smart pointers expect the pointee to be passed to their
ctor, but the ctor is only called once.


It depends on the type of smart pointer you're using.

Somthing like this might work.

struct X
{
smartptr z;
X()
: x( a ? 0 : new Y )
{}
};
Nov 26 '05 #3
Matthias Kaeppler wrote:
Hi,

I'm having a hard time figuring out how I can initialize a smart pointer
based on a certain condition:

if something then
ptr = 0; // init with NULL
else
ptr = new XYZ; // init with a sane value
endif

I know assignment doesn't work for a smart pointer unless the assigned
value is a smart pointer itself.

Any ideas how I can trick the compiler to do what I need? The problem is
simply that smart pointers expect the pointee to be passed to their
ctor, but the ctor is only called once.

Regards,
Matthias Kaeppler


Surely this works

if something then
ptr = SmartPtr(0); // init with NULL
else
ptr = SmartPtr(new XYZ); // init with a sane value

where SmartPtr is your smart pointer class.

Alternatively you could write a function returning a regular pointer, or
you could use the conditional operator, but the above seems the most
general solution.

john
Nov 26 '05 #4
Matthias Kaeppler wrote:
I know assignment doesn't work for a smart pointer unless the assigned
value is a smart pointer itself.


In addition the other answer, one obvious one is this: fix the smart
pointer class so that you can assign regular pointers to it which
become owned.

If you are using auto_ptr, the reset() function does that:

auto_ptr<char> x;

x.reset(new char [20]);

It's ugly, but that's what you get when a committee finally agrees on
something something: a bastard child with a dozen fathers.

A decent smart pointer class has operators that let it interoperate
smoothly with dumb pointers, such as a T * operator so that the smart
pointer objects can appear to be directly passed into functions that
expect T * pointers, equality/inequality operators so that smart
pointers can be copmared with dumb pointers, an assignment operator so
that a dumb pointer can be imported easily and becomes owned, etc.

Remember, even if the class designer didn't provide some operator, you
can write one yourself outside of the class, since operators can be
non-member functions:

template <class T>
poor_smart_ptr< T> &operator = (poor_smart_ptr <T> &lhs, T *rhs)
{
lhs = poor_smart_ptr< T>(rhs);
return lhs;
}

There, now you can assign T * pointers to a poor_smart_ptr< T> object.

See? NON-membership can have its privileges too! :)

Nov 27 '05 #5

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

Similar topics

13
1620
by: christopher diggins | last post by:
What I am trying to answer is, what the most prominent motivation for implenting and using smart pointers in C++ is. Is it primarily to reduce bugs resulting from memory access errors or primarily to permit lazy deallocation designs (i.e. designs that rely on non-determined non-fixed non-explicit deallocation of memory)? Obviously both are advantages, but I want to know if programmers are finding that lazy deallocation is one of the major...
9
2155
by: christopher diggins | last post by:
I would like to survey how widespread the usage of smart pointers in C++ code is today. Any anecdotal experience about the frequency of usage of smart pointer for dynamic allocation in your own code or other people's code you have come across would be appreciated. I am also trying to identify the likelihood nad frequency of scenarios where smart pointer solutions would not be appropriate, i.e. for some reason such as performance or...
27
3412
by: Susan Baker | last post by:
Hi, I'm just reading about smart pointers.. I have some existing C code that I would like to provide wrapper classes for. Specifically, I would like to provide wrappers for two stucts defined as ff: typedef struct { float *data ; int count ;
3
2301
by: maadhuu | last post by:
Hello, I have tried this smart pointer implementation, but it is not working and I am not able to figure out why .......Also, can you please suggest more effective way/s of doing the same ??? Thank you, Maadhuu. //Smart.h #ifndef _SMART_H
8
5153
by: Axter | last post by:
I normally use a program call Doxygen to document my source code.(http://www.stack.nl/~dimitri/doxygen) This method works great for small and medium size projects, and you can get good documentation like the following: http://axter.com/smartptr Now I'm on a client site, and I'm trying to create the same type of documentation on a very large project. I ran the Doxygen program, and it ran for over 16 hours, before I had
5
7805
by: Boris | last post by:
I've a class C with a smart pointer (I use boost::shared_ptr) which is initialized in the constructor: class C { boost::shared_ptr<D> d; public: C() : d(new d()) { } }; When the program starts class C is instantiated quite a lot. As all the
92
5119
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers, but I just don't know. I don't like them because I don't trust them. I use new and delete on pure pointers instead. Do you use smart pointers?
33
5083
by: Ney André de Mello Zunino | last post by:
Hello. I have written a simple reference-counting smart pointer class template called RefCountPtr<T>. It works in conjunction with another class, ReferenceCountable, which is responsible for the actual counting. Here is the latter's definition: // --- Begin ReferenceCountable.h ---------- class ReferenceCountable
54
12019
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining the advantages of smart pointers endlessly (which are currently used in all our C++ software; we use the Boost smart pointers) as I'm seriously concerned that there is a shift to raw pointers. We are not developing system software but rather...
0
10219
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, 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...
0
10049
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9998
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,...
0
9865
tracyyun
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...
0
8876
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
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...
0
6675
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();...
1
3967
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3567
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.