This code is from c++ faq in section 11 :
void someCode()
{
char memory[sizeof(Fred)];
void* p = memory;
Fred* f = new(p) Fred();
f->~Fred(); // Explicitly call the destructor for the placed
object
}
Here we r passing address of stack memory to new .
New is used to allocate memory on heap . Then how can we pass address
of
stack memory to new operator . It is confusing .
Regards ,
Mangesh . 15 4663
* mangesh: This code is from c++ faq in section 11 :
void someCode() { char memory[sizeof(Fred)]; void* p = memory; Fred* f = new(p) Fred();
Should be
Fred* f = ::new(p) Fred();
f->~Fred(); // Explicitly call the destructor for the placed object }
Here we r passing address of stack memory to new . New is used to allocate memory on heap . Then how can we pass address of stack memory to new operator . It is confusing .
The basic placement new operator (there are an infinity of them, but the
basic one from <new>) constructs an object in a specified region of memory.
You shouldn't use it because it's a low-level mechanism to subvert the
ordinary language rules and as such is fraught with dangers, even more
than with casts, e.g., as just one example, here that 'memory' may not
be properly aligned for an object of type 'Fred', and in particular:
* A novice should /never/ use the basic placement new.
Most uses of (the basic) placement new are better expressed using
standard library classes such as std::vector, which do the dangerous
stuff for you, in a safe way, so that you don't even see it.
--
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?
mangesh wrote: void someCode() { char memory[sizeof(Fred)]; void* p = memory; Fred* f = new(p) Fred(); f->~Fred(); // Explicitly call the destructor for the placed object }
Here we r passing address of stack memory to new .
I find it baffling that you can take the time to place weird spaces
around your punctuation, but the three letters in the word "are" are
too much effort in the name of readability when you're asking others to
help you.
Anyway, yes, you're doing a placement-new on a stack-allocated array.
New is used to allocate memory on heap .
Not quite -- it allocates memory on the free store, which may or may
not be implemented in terms of the heap. It may also be overridden by
a custom allocator, which incidentally would likely make use of
placement new.
Then how can we pass address of stack memory to new operator . It is confusing .
Because a placement new doesn't allocate memory, it uses memory that
you've allocated for it. That's the entire point. It skips the
allocation step and goes straight to construction. It doesn't care
what part of memory the pointer points to, as long as it can be written
to.
Imagine, for example, implementing a custom allocator for small objects
based on a fixed-size arena allocated as a single chunk. That chunk
might be member data of an allocator class, and could therefore be
stack-allocated. Of course, if the allocator class was instantiated
dynamically, then its member data would live on the free store. Since
either could be the case, it would pose a real problem if the compiler
couldn't handle doing a placement new into stack-allocated memory.
Luke
Hi ,
thanks for reply .
Now in given case is statement " f->~Fred() ; " really needed .
Since memory is on stack it will be automaticaly deleted on exiting
function .
Regards
Mangesh .
Luke Meyers wrote: mangesh wrote: void someCode() { char memory[sizeof(Fred)]; void* p = memory; Fred* f = new(p) Fred(); f->~Fred(); // Explicitly call the destructor for the placed object }
Here we r passing address of stack memory to new .
I find it baffling that you can take the time to place weird spaces around your punctuation, but the three letters in the word "are" are too much effort in the name of readability when you're asking others to help you.
Anyway, yes, you're doing a placement-new on a stack-allocated array.
New is used to allocate memory on heap .
Not quite -- it allocates memory on the free store, which may or may not be implemented in terms of the heap. It may also be overridden by a custom allocator, which incidentally would likely make use of placement new.
Then how can we pass address of stack memory to new operator . It is confusing .
Because a placement new doesn't allocate memory, it uses memory that you've allocated for it. That's the entire point. It skips the allocation step and goes straight to construction. It doesn't care what part of memory the pointer points to, as long as it can be written to.
Imagine, for example, implementing a custom allocator for small objects based on a fixed-size arena allocated as a single chunk. That chunk might be member data of an allocator class, and could therefore be stack-allocated. Of course, if the allocator class was instantiated dynamically, then its member data would live on the free store. Since either could be the case, it would pose a real problem if the compiler couldn't handle doing a placement new into stack-allocated memory.
Luke
mangesh wrote: Hi , thanks for reply . Now in given case is statement " f->~Fred() ; " really needed . Since memory is on stack it will be automaticaly deleted on exiting function .
Please don't top post.
The memory won't be deleted, it will no longer be usable so any object
created on the stack with placement new will be left in limbo.
That's one reason doing so is a daft idea.
--
Ian Collins.
In message <11************ **********@i40g 2000cwc.googleg roups.com>,
mangesh <ma************ @walla.com> writes
Please don't top-post. I've moved your reply to where it should be. Luke Meyers wrote: mangesh wrote: > void someCode() > { > char memory[sizeof(Fred)]; > void* p = memory; > Fred* f = new(p) Fred(); > f->~Fred(); // Explicitly call the destructor for the placed > object > } >
[big snip]
Hi , thanks for reply . Now in given case is statement " f->~Fred() ; " really needed .
Yes.
Since memory is on stack it will be automaticaly deleted on exiting function .
No. The memory will be deallocated, but the object's destructor is not
called unless you do so explicitly.
Allocating memory, constructing an object, destroying the object and
freeing the memory are four separate steps.
--
Richard Herring
Alf P. Steinbach posted: Fred* f = new(p) Fred();
Should be
Fred* f = ::new(p) Fred();
Could you please explain that?
--
Frederick Gotham
mangesh posted: char memory[sizeof(Fred)];
This array isn't necessarily suitably aligned. You need to make sure it's
suitably aligned by either:
(1) Dynamically allocating it
(2) Using union trickery
(3) Using boost's "align_for" (or whatever it's called)
--
Frederick Gotham
* Frederick Gotham: Alf P. Steinbach posted:
Fred* f = new(p) Fred(); Should be
Fred* f = ::new(p) Fred();
Could you please explain that?
Unqualified placement new might invoke a custom Fred allocation function
instead of the basic placement new.
--
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?
Alf P. Steinbach posted: * Frederick Gotham: Alf P. Steinbach posted:
Fred* f = new(p) Fred(); Should be
Fred* f = ::new(p) Fred();
Could you please explain that?
Unqualified placement new might invoke a custom Fred allocation
function instead of the basic placement new.
When you want to use "placement new", would it be wise to always use:
::new(p) Type();
(I realise it won't make a difference with intrinsic types, but it's
consistent nonetheless for dealing with class types).
--
Frederick Gotham This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Philip Lawatsch |
last post by:
Hi,
I have some questions about whats written in
http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14
(Describing some memory pool)
#1 From what i understand this will also work for new x and delete
x, or did i misunderstand something ?
and,
|
by: jr |
last post by:
Sorry for this very dumb question, but I've clearly got a long way to go!
Can someone please help me pass an array into a function. Here's a starting
point.
void TheMainFunc()
{
// Body of code...
TCHAR myArray;
DoStuff(myArray);
|
by: Jonas Rundberg |
last post by:
Hi
I just started with c++ and I'm a little bit confused where stuff
go...
Assume we have a class:
class test {
private:
int arr;
};
|
by: candy |
last post by:
hi all,
Is there is any way in the C language by which I can get the
address of a statement? For eg,consider the following simple program:
1. #include<stdio.h>
2.
3. int main(void){
4. int variable;
|
by: John Pass |
last post by:
Hi,
In the attached example, I do understand that the references are not changed
if an array is passed by Val. What I do not understand is the result of line
99 (If one can find this by line number) which is the last line of the
following sub routine:
' procedure modifies elements of array and assigns
' new reference (note ByVal)
Sub FirstDouble(ByVal array As Integer())
Dim i As Integer
| |
by: rob.kirkpatrick |
last post by:
Hello
I need to populate an array of char arrays at run-time. A very
simplifed version of the code is below.
char ** list should contain cnt char arrays. The values of char ** list
are set by the function foo(). A pointer to char ** list is passed to
foo() as an argument.
The problem is that when foo() returns, char ** list contains rubbish
|
by: shanemh |
last post by:
I'm starting out with c++ and for some reason I cant get my brain
around this one:
If I have the following:
void Foo (someClass& x)
{}
int Main (void)
{
|
by: Lagarde Sébastien |
last post by:
Hello,
I write code to debug new call with following macro:
#define new (MemoryManager::Get().setOwner (__FILE__, __LINE__, _FUNCTION-),
FALSE) ? NULL : new
The setOwner allow to save the current file, line and function:
setOwner(const char *file, const u32 line, const char *func)
{
|
by: sanjay |
last post by:
Hi,
I have a doubt about passing values to a function accepting string.
======================================
#include <iostream>
using namespace std;
int main()
{
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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: 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...
|
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: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
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...
| |