if we have a class or struct that contains a variable (an array for
example) declared inside its constructor using the new keyword, will
creating an instance of this class without using new cause the
internal array to be created on the stack, or the heap?
yes, even if you create an object on stack (without new
keyword) its internal data will be allocated on heap if new is used in class construcor (there might be exceptions when placement new is used to allocate data on stack - we'll see it later). Common example is allocating an array:
int main() {
int* t = new int[100]; // pointer is on stack, data on the heap
//...
}
and similarly:
class A{
public:
A(){
int* t = new int[100];
std::cout<<"heap used\n";
delete t;
}
};
int main(int argc, char** argv) {
A a1;
// ...
}
prints:
heap used
and indeed, 100 int
s have been allocated (and deleted) on the free store.
If you need to specify the memory location you can use placement new:
char buf[1024];
string* p = new (buf) string("on stack"); // pointer is on stack,
// data on the stack