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 64179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T18:44:57+00:00 2026-05-10T18:44:57+00:00

I have a class that contains a dynamically allocated array, say class A {

  • 0

I have a class that contains a dynamically allocated array, say

class A {     int* myArray;     A()     {         myArray = 0;     }     A(int size)     {         myArray = new int[size];     }     ~A()     {         // Note that as per MikeB's helpful style critique, no need to check against 0.         delete [] myArray;     } } 

But now I want to create a dynamically allocated array of these classes. Here’s my current code:

A* arrayOfAs = new A[5]; for (int i = 0; i < 5; ++i) {     arrayOfAs[i] = A(3); } 

But this blows up terribly. Because the new A object created (with the A(3) call) gets destructed when the for loop iteration finishes, and this means that the internal myArray of that A instance gets delete []-ed.

So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I’m hoping to avoid:

  • Creating a copy constructor for A.
  • Using vector<int> and vector<A> so I don’t have to worry about all this.
  • Instead of having arrayOfAs be an array of A objects, have it be an array of A* pointers.

I would think this is just some beginners thing where there’s a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.

(Also, style critiques appreciated, since it’s been a while since I did C++.)

Update for future viewers: All of the answers below are really helpful. Martin’s is accepted because of the example code and the useful ‘rule of 4,’ but I really suggest reading them all. Some are good, succinct statements of what’s wrong, and some point out correctly how and why vectors are a good way to go.

  • 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. 2026-05-10T18:44:58+00:00Added an answer on May 10, 2026 at 6:44 pm

    For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.

    If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).

    • Constructor
    • Destructor
    • Copy Constructor
    • Assignment Operator
    • Move Constructor (C++11)
    • Move Assignment (C++11)

    This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.

    The copy constructor is the hard one to get correct (it’s non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.

    See below for full details on the absolute minimum for a class containing a pointer to an array of integers.

    Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.

    class A {      std::vector<int>   mArray;     public:         A(){}         A(size_t s) :mArray(s)  {} }; 

    Looking at your problem:

    A* arrayOfAs = new A[5]; for (int i = 0; i < 5; ++i) {     // As you surmised the problem is on this line.     arrayOfAs[i] = A(3);      // What is happening:     // 1) A(3) Build your A object (fine)     // 2) A::operator=(A const&) is called to assign the value     //    onto the result of the array access. Because you did     //    not define this operator the compiler generated one is     //    used. } 

    The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.

    The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

    The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

    So the minimum for a class that contains a pointer:

    class A {     size_t     mSize;     int*       mArray;     public:          // Simple constructor/destructor are obvious.          A(size_t s = 0) {mSize=s;mArray = new int[mSize];}         ~A()             {delete [] mArray;}           // Copy constructor needs more work          A(A const& copy)          {              mSize  = copy.mSize;              mArray = new int[copy.mSize];               // Don't need to worry about copying integers.              // But if the object has a copy constructor then              // it would also need to worry about throws from the copy constructor.              std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);           }           // Define assignment operator in terms of the copy constructor          // Modified: There is a slight twist to the copy swap idiom, that you can          //           Remove the manual copy made by passing the rhs by value thus          //           providing an implicit copy generated by the compiler.          A& operator=(A rhs) // Pass by value (thus generating a copy)          {              rhs.swap(*this); // Now swap data with the copy.                               // The rhs parameter will delete the array when it                               // goes out of scope at the end of the function              return *this;          }          void swap(A& s) noexcept          {              using std::swap;              swap(this.mArray,s.mArray);              swap(this.mSize ,s.mSize);          }           // C++11          A(A&& src) noexcept              : mSize(0)              , mArray(NULL)          {              src.swap(*this);          }          A& operator=(A&& src) noexcept          {              src.swap(*this);     // You are moving the state of the src object                                   // into this one. The state of the src object                                   // after the move must be valid but indeterminate.                                   //                                   // The easiest way to do this is to swap the states                                   // of the two objects.                                   //                                   // Note: Doing any operation on src after a move                                    // is risky (apart from destroy) until you put it                                    // into a specific state. Your object should have                                   // appropriate methods for this.                                   //                                    // Example: Assignment (operator = should work).                                   //          std::vector() has clear() which sets                                   //          a specific state without needing to                                   //          know the current state.              return *this;          }     } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

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

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

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

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

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer A smart pointer is still a pointer, so such an… May 12, 2026 at 6:26 pm
  • Editorial Team
    Editorial Team added an answer If your target audience is running Windows and IE, and… May 12, 2026 at 6:26 pm
  • Editorial Team
    Editorial Team added an answer Well SSRS for SQL Server is designed to be used… May 12, 2026 at 6:26 pm

Related Questions

I have a class that contains some private attributes. What I would like to
I have a test program called ftest. It loads .so files that contain tests
Background I am developing a highly modular application in pure Action Script 3 (we
I work for an Architecture firm and I am creating a plug-in for a

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.