Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 621381
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T18:52:04+00:00 2026-05-13T18:52:04+00:00

Consider the following code: class A { B* b; // an A object owns

  • 0

Consider the following code:

class A
{
    B* b; // an A object owns a B object

    A() : b(NULL) { } // we don't know what b will be when constructing A

    void calledVeryOften(…)
    {
        if (b)
            delete b;

        b = new B(param1, param2, param3, param4);
    }
};

My goal: I need to maximize performance, which, in this case, means minimizing the amount of memory allocations.

The obvious thing to do here is to change B* b; to B b;. I see two problems with this approach:

  • I need to initialize b in the constructor. Since I don’t know what b will be, this means I need to pass dummy values to B’s constructor. Which, IMO, is ugly.
  • In calledVeryOften(), I’ll have to do something like this: b = B(…), which is wrong for two reasons:
    • The destructor of b won’t be called.
    • A temporary instance of B will be constructed, then copied into b, then the destructor of the temporary instance will be called. The copy and the destructor call could be avoided. Worse, calling the destructor could very well result in undesired behavior.

So what solutions do I have to avoid using new? Please keep in mind that:

  • I only have control over A. I don’t have control over B, and I don’t have control over the users of A.
  • I want to keep the code as clean and readable as possible.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T18:52:04+00:00Added an answer on May 13, 2026 at 6:52 pm

    I liked Klaim’s answer, so I wrote this up real fast. I don’t claim perfect correctness but it looks pretty good to me. (i.e., the only testing it has is the sample main below)

    It’s a generic lazy-initializer. The space for the object is allocated once, and the object starts at null. You can then create, over-writing previous objects, with no new memory allocations.

    It implements all the necessary constructors, destructor, copy/assignment, swap, yadda-yadda. Here you go:

    #include <cassert>
    #include <new>
    
    template <typename T>
    class lazy_object
    {
    public:
        // types
        typedef T value_type;
        typedef const T const_value_type;
        typedef value_type& reference;
        typedef const_value_type& const_reference;
        typedef value_type* pointer;
        typedef const_value_type* const_pointer;
    
        // creation
        lazy_object(void) :
        mObject(0),
        mBuffer(::operator new(sizeof(T)))
        {
        }
    
        lazy_object(const lazy_object& pRhs) :
        mObject(0),
        mBuffer(::operator new(sizeof(T)))
        {
            if (pRhs.exists())
            {
                mObject = new (buffer()) T(pRhs.get());
            }
        }
    
        lazy_object& operator=(lazy_object pRhs)
        {
            pRhs.swap(*this);
    
            return *this;
        }
    
        ~lazy_object(void)
        {
            destroy();
            ::operator delete(mBuffer);
        }
    
        // need to make multiple versions of this.
        // variadic templates/Boost.PreProccesor
        // would help immensely. For now, I give
        // two, but it's easy to make more.
        void create(void)
        {
            destroy();
            mObject = new (buffer()) T();
        }
    
        template <typename A1>
        void create(const A1 pA1)
        {
            destroy();
            mObject = new (buffer()) T(pA1);
        }
    
        void destroy(void)
        {
            if (exists())
            {
                mObject->~T();
                mObject = 0;
            }
        }
    
        void swap(lazy_object& pRhs)
        {
            std::swap(mObject, pRhs.mObject);
            std::swap(mBuffer, pRhs.mBuffer);
        }
    
        // access
        reference get(void)
        {
            return *get_ptr();
        }
    
        const_reference get(void) const
        {
            return *get_ptr();
        }
    
        pointer get_ptr(void)
        {
            assert(exists());
            return mObject;
        }
    
        const_pointer get_ptr(void) const
        {
            assert(exists());
            return mObject;
        }
    
        void* buffer(void)
        {
            return mBuffer;
        }
    
        // query
        const bool exists(void) const
        {
            return mObject != 0;
        }
    
    private:
        // members
        pointer mObject;
        void* mBuffer;
    };
    
    // explicit swaps for generality
    template <typename T>
    void swap(lazy_object<T>& pLhs, lazy_object<T>& pRhs)
    {
        pLhs.swap(pRhs);
    }
    
    // if the above code is in a namespace, don't put this in it!
    // specializations in global namespace std are allowed.
    namespace std
    {
        template <typename T>
        void swap(lazy_object<T>& pLhs, lazy_object<T>& pRhs)
        {
            pLhs.swap(pRhs);
        }
    }
    
    // test use
    #include <iostream>
    
    int main(void)
    {
        // basic usage
        lazy_object<int> i;
        i.create();
        i.get() = 5;
    
        std::cout << i.get() << std::endl;
    
        // asserts (not created yet)
        lazy_object<double> d;
        std::cout << d.get() << std::endl;
    }
    

    In your case, just create a member in your class: lazy_object<B> and you’re done. No manual releases or making copy-constructors, destructors, etc. Everything is taken care of in your nice, small re-usable class. 🙂

    EDIT

    Removed the need for vector, should save a bit of space and what-not.

    EDIT2

    This uses aligned_storage and alignment_of to use the stack instead of heap. I used boost, but this functionality exists in both TR1 and C++0x. We lose the ability to copy, and therefore swap.

    #include <boost/type_traits/aligned_storage.hpp>
    #include <cassert>
    #include <new>
    
    template <typename T>
    class lazy_object_stack
    {
    public:
        // types
        typedef T value_type;
        typedef const T const_value_type;
        typedef value_type& reference;
        typedef const_value_type& const_reference;
        typedef value_type* pointer;
        typedef const_value_type* const_pointer;
    
        // creation
        lazy_object_stack(void) :
        mObject(0)
        {
        }
    
        ~lazy_object_stack(void)
        {
            destroy();
        }
    
        // need to make multiple versions of this.
        // variadic templates/Boost.PreProccesor
        // would help immensely. For now, I give
        // two, but it's easy to make more.
        void create(void)
        {
            destroy();
            mObject = new (buffer()) T();
        }
    
        template <typename A1>
        void create(const A1 pA1)
        {
            destroy();
            mObject = new (buffer()) T(pA1);
        }
    
        void destroy(void)
        {
            if (exists())
            {
                mObject->~T();
                mObject = 0;
            }
        }
    
        // access
        reference get(void)
        {
            return *get_ptr();
        }
    
        const_reference get(void) const
        {
            return *get_ptr();
        }
    
        pointer get_ptr(void)
        {
            assert(exists());
            return mObject;
        }
    
        const_pointer get_ptr(void) const
        {
            assert(exists());
            return mObject;
        }
    
        void* buffer(void)
        {
            return mBuffer.address();
        }
    
        // query
        const bool exists(void) const
        {
            return mObject != 0;
        }
    
    private:
        // types
        typedef boost::aligned_storage<sizeof(T),
                    boost::alignment_of<T>::value> storage_type;
    
        // members
        pointer mObject;
        storage_type mBuffer;
    
        // non-copyable
        lazy_object_stack(const lazy_object_stack& pRhs);
        lazy_object_stack& operator=(lazy_object_stack pRhs);
    };
    
    // test use
    #include <iostream>
    
    int main(void)
    {
        // basic usage
        lazy_object_stack<int> i;
        i.create();
        i.get() = 5;
    
        std::cout << i.get() << std::endl;
    
        // asserts (not created yet)
        lazy_object_stack<double> d;
        std::cout << d.get() << std::endl;
    }
    

    And there we go.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 375k
  • Answers 375k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I got it! Apparently RewriteCond needs the whole directory structure… May 14, 2026 at 8:17 pm
  • Editorial Team
    Editorial Team added an answer I believe that the full-trust option is only available as… May 14, 2026 at 8:17 pm
  • Editorial Team
    Editorial Team added an answer The regular expression you need is: X[-\d.]+Y[-\d.]+ Here is how… May 14, 2026 at 8:17 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.