473,788 Members | 3,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling container constructor explicitly

I'm trying to write some code that calls the constructors of STL
containers explicitly, and I can't get it to compile. A sample program
is below. One compiler complains about the last two lines (the map
constructor calls), saying that I'm trying to take the address of a
constructor. Another compiler complains about all four of the last
lines, just saying "invalid use of class". What is the correct syntax
for calling a container constructor explicitly?

You're probably wondering why I'm not calling "new" instead of malloc
and the constructor. It's because what I really need to do is to call
a proprietary memory allocation function (i.e., not malloc) and then
call a parameterized constructor on the returned space. So neither
"new" nor "placement new" will work for me.

Thanks for the help!

- Dave
#include <vector>
#include <map>
#include <cstdlib>

int
main()
{
typedef std::vector<int VecType;
typedef std::map<int, intMapType;

VecType v, *vp;
MapType m, *mp;

vp = (VecType *)malloc(sizeof (VecType));
mp = (MapType *)malloc(sizeof (MapType));

// call constructors
v.VecType::vect or();
vp->VecType::vecto r();
m.MapType::map( );
mp->MapType::map() ;
}

Jul 16 '06 #1
6 2466
* daveb:
I'm trying to write some code that calls the constructors of STL
containers explicitly, and I can't get it to compile.
The following is an implicit constructor call ("implicit" means "implied
or understood though not directly expressed"):

std::vector<int v;

The following is an explicit constructor call ("explicit" means "fully
and clearly expressed; leaving nothing implied"):

std::vector<int >();

The last one creates a temporary; see the FAQ.

A sample program
is below. One compiler complains about the last two lines (the map
constructor calls), saying that I'm trying to take the address of a
constructor. Another compiler complains about all four of the last
lines, just saying "invalid use of class". What is the correct syntax
for calling a container constructor explicitly?
In general, supplying a constructor argument list after a type
specification is the correct syntax for calling a constructor
explicitly. But that's not a formal view: it's just a summary of the
effect of the formal syntax rules. Also, note that the opposite does
not hold: int() constructs the int value 0, but int has no constructor.

You're probably wondering why I'm not calling "new" instead of malloc
and the constructor. It's because what I really need to do is to call
a proprietary memory allocation function (i.e., not malloc) and then
call a parameterized constructor on the returned space. So neither
"new" nor "placement new" will work for me.
Placement new is exactly for that.

But it's a rather silly thing, nay, STRONGERWORD thing, to do.

A vector object by itself takes up just a few bytes. The contents are
typically allocated separately. To take charge of the allocation for
vector contents you need to specify an allocator type in the type
definition.

#include <vector>
#include <map>
#include <cstdlib>

int
main()
{
typedef std::vector<int VecType;
typedef std::map<int, intMapType;

VecType v, *vp;
At this point v has been constructed and vp is uninitialized pointer.

MapType m, *mp;

vp = (VecType *)malloc(sizeof (VecType));
mp = (MapType *)malloc(sizeof (MapType));

// call constructors
v.VecType::vect or();
vp->VecType::vecto r();
Syntax error.

The way to call constructors on raw storage is to use placement new, but
see above: it's STRONGERWORD for std::vector, check out allocators.
--
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?
Jul 16 '06 #2
daveb wrote:
What is the correct syntax for calling a container constructor explicitly?
The same as for any other class: none.
You're probably wondering why I'm not calling "new" instead of malloc
and the constructor. It's because what I really need to do is to call
a proprietary memory allocation function (i.e., not malloc) and then
call a parameterized constructor on the returned space. So neither
"new" nor "placement new" will work for me.
Strange. "placement new" is habitually used for that.

If you want that the contained objects, not the container object itself, use
your allocation function, write an adequate allocator and use it.

--
Salu2
Jul 16 '06 #3
daveb wrote:
I'm trying to write some code that calls the constructors of STL
containers explicitly, and I can't get it to compile. A sample program
is below. One compiler complains about the last two lines (the map
constructor calls), saying that I'm trying to take the address of a
constructor. Another compiler complains about all four of the last
lines, just saying "invalid use of class". What is the correct syntax
for calling a container constructor explicitly?
That depends on what you mean by calling the constructor explictly. The
standard reserves this language for the function notation of a type
conversion like

std::string( "hello world" );

Despite that, placement new is what is semantically closest to calling a
constructor.
You're probably wondering why I'm not calling "new" instead of malloc
and the constructor. It's because what I really need to do is to call
a proprietary memory allocation function (i.e., not malloc) and then
call a parameterized constructor on the returned space. So neither
"new" nor "placement new" will work for me.
Huh? Isn't this exactly what placement new is doing: construct an object at
a specified location in memory by invoking the constructor appropriate for
the given arguments?
>
Thanks for the help!

- Dave
#include <vector>
#include <map>
#include <cstdlib>

int
main()
{
typedef std::vector<int VecType;
typedef std::map<int, intMapType;

VecType v, *vp;
MapType m, *mp;

vp = (VecType *)malloc(sizeof (VecType));
mp = (MapType *)malloc(sizeof (MapType));

// call constructors
v.VecType::vect or();
vp->VecType::vecto r();
m.MapType::map( );
mp->MapType::map() ;
}

That won't fly as constructors don't have names, are not found by name
lookup and therefore cannot be called like member functions.

What about:

VecType v;
VecType* vp = (VecType *)malloc(sizeof (VecType));
new ( vp ) VecType ();

MapType m;
MapType* mp = (MapType *)malloc(sizeof (MapType));
new ( mp ) MapType ();
Best

Kai-Uwe
Jul 16 '06 #4
daveb wrote:
>
You're probably wondering why I'm not calling "new" instead of malloc
and the constructor. It's because what I really need to do is to call
a proprietary memory allocation function (i.e., not malloc) and then
call a parameterized constructor on the returned space. So neither
"new" nor "placement new" will work for me.
I'm not sure why you jump to the conclusion placement new will not
work. It appears to be exactly what you want.

You can't call constructors PERIOD. The best you can do is create
objects with a different allocation function (i.e., placement new).

You do know that the memory used by a standard container itself
is tiny compared with the memory for the contained objects which
you probably need to write an allocation function for as well.
Jul 16 '06 #5
My thanks to everyone who responded. I was under the impression that
placement new could be used only to call an object's *default*
constructor. But I infer from the code that Kai-Uwe provided that
parameterized constructors can be called by providing the parameters
within parentheses at the end of the statement. If so, (as most of you
noted) that's exactly what I need.

BTW, this is embedded firmware. I need the proprietary memory
allocator because the container and its contents must reside in a
"persistent " area of memory that is not initialized at boot time. I
already intended to provide a custom allocator to the container, but
this custom allocator will be called only for the *contents* of the
container, correct? I also need the container itself to live in the
persistent region of memory.

- Dave

Jul 17 '06 #6
* Julián Albo:
daveb wrote:
>What is the correct syntax for calling a container constructor explicitly?

The same as for any other class: none.
Do not perpetuate urban myths, please.

--
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?
Jul 17 '06 #7

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

Similar topics

3
3137
by: Christian Dieterich | last post by:
Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? Thank,
8
2983
by: trying_to_learn | last post by:
Why do we need to explicitly call the copy constructor and the operator = , for base class and member objects in composition? ....book says "You must explicitly call the GameBoard copy-constructor or the default constructor is automatically called instead" Why cant the compiler do this on its own. if we are making an object through copr construction for an inherited class , then why not simply call the corresponding copy constructors for...
14
2720
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
1
1276
by: JezB | last post by:
In my Page_Load event of all my web app Pages and UserControls I instantiate the same library class "TextResources" (to take care of reading presentation text strings from localizable resource files). Within this class's constructor I want to deduce the name of the calling control without having to pass it in. As this can either be a Page or a UserControl I cannot use Request.URL since this only gives you the current page. Any ideas ?
2
3218
by: Sathyaish | last post by:
How does a constructor of one class call another of the same class? When would this mechanism make sense or be required? PS: Two instances I saw are: (a) While using the Singleton pattern (b) While using the Factory pattern
12
5816
by: st_ev_fe | last post by:
I've noticed that when constructing a subclass, the base class get's it's contructors called. Is there some way to avoid this? The base class has one variable, which gets initialised to 0. The subclass's constructor sets this variable to a real value. So first the variable is set to 0, the variable is never used before it once again gets set to a real value. It's a waste. Any ideas anyone?
11
7410
by: PengYu.UT | last post by:
The following program calls the normal constructor and the copy constructor. By calling the copy constuctor is redundandant, all I want is only a vector of a trial object. Is there any way to avoid the use of the copy constructor? #include <vector> #include <iostream>
2
3551
by: mikepolitowski | last post by:
Hi folks, I am have been trying to solve this problem for quite some time now and would appreciate any advice. I have been trying to call a code-behind function that is defined in my aspx.cs from within a DataList <ItemTemplate> block using the <%# %> syntax. I would not have written here if I had not spent over 6 hours trying to find a solution to this problem again any advice is greatly appreciated. I have included a code snippet...
80
2449
by: Boltar | last post by:
Hi I need to store a number of integer values which I will then search on later to see if they exist in my container. Can someone tell me which container would be quickest for finding these values? I can't use a plain C array (unless I make it 2^32 in size!) since I don't know the max integer value. Thanks for any help
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
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,...
0
10363
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
8993
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...
0
6749
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();...
0
5398
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...
1
4069
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
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
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...

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.