473,793 Members | 2,922 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy-less initialization of a TR1 array

zr
Hi,

Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
Vice-versa is easy to do, simply use std::t1::array: :data() and assign
the returned value to the c-style pointer;

if STL does not support this, is there any other library that has such
a container (maybe BOOST)?

Here is an example of what i have in mind:

#include <array>
using namespace std::tr1;

int main()
{

int cArray[] = { 1 , 2, 3, 4};

array<int,4tr1A rray(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory

tr1Array[0] = 42;
assert(tr1Array[0] == cArray[0] == 42); // Both point to same memory

tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch

return 0;
}
Nov 10 '08 #1
5 3185
On Nov 10, 12:30*pm, zr <zvir...@gmail. comwrote:
Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
There is a way. Disclaimer: it is not blessed by the standard.
Vice-versa is easy to do, simply use std::t1::array: :data() and assign
the returned value to the c-style pointer;

if STL does not support this, is there any other library that has such
a container (maybe BOOST)?

Here is an example of what i have in mind:

#include <array>
using namespace std::tr1;

int main()
{

int cArray[] = { 1 , 2, 3, 4};

array<int,4tr1A rray(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory
Here you do:

// make sure that the binary layouts of
// array<and C-array are the same
typedef int static_assert[sizeof(array<in t,4>) == sizeof(cArray) ?
1 : -1];
// now do the hack
array<int,4>& tr1Array = reinterpret_cas t<array<int,4>& >(cArray);
tr1Array[0] = 42;
assert(tr1Array[0] == cArray[0] == 42); // Both point to same memory

tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch

return 0;

}
--
Max

Nov 10 '08 #2
zr
On Nov 10, 3:52*pm, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
On Nov 10, 12:30*pm, zr <zvir...@gmail. comwrote:
Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?

There is a way. Disclaimer: it is not blessed by the standard.
Vice-versa is easy to do, simply use std::t1::array: :data() and assign
the returned value to the c-style pointer;
if STL does not support this, is there any other library that has such
a container (maybe BOOST)?
Here is an example of what i have in mind:
#include <array>
using namespace std::tr1;
int main()
{
int cArray[] = { 1 , 2, 3, 4};
array<int,4tr1A rray(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory

Here you do:

* * // make sure that the binary layouts of
* * // array<and C-array are the same
* * typedef int static_assert[sizeof(array<in t,4>) == sizeof(cArray) ?
1 : -1];
* * // now do the hack
* * array<int,4>& tr1Array = reinterpret_cas t<array<int,4>& >(cArray);
tr1Array[0] = 42;
assert(tr1Array[0] == cArray[0] == 42); // Both point to same memory
tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch
return 0;
}

--
Max
Thanks, Max. I wonder if there is a similar trick for casting a
dynamic array to a std::vector...
Nov 10 '08 #3
On Nov 10, 7:30*am, zr <zvir...@gmail. comwrote:
Hi,

Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
Vice-versa is easy to do, simply use std::t1::array: :data() and assign
the returned value to the c-style pointer;

if STL does not support this, is there any other library that has such
a container (maybe BOOST)?

Here is an example of what i have in mind:

#include <array>
using namespace std::tr1;

int main()
{

int cArray[] = { 1 , 2, 3, 4};

array<int,4tr1A rray(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory

tr1Array[0] = 42;
assert(tr1Array[0] == cArray[0] == 42); // Both point to same memory

tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch

return 0;

}- Hide quoted text -

- Show quoted text -
The issue with doing that is that once you have a container, you
should be able to do whatever you want with it (e.g. changing it's
elements). So unless you put it behind an interface (e.g. a function
or class) that returns a const container, it won't work.

You can use constant built in arrays by passing around a pair of it's
begin and end const iterators. Client code that uses it only knows
that it's a const container and has no knowledge of what kind of
container.

HTH
Nov 10 '08 #4
zr wrote:
On Nov 10, 3:52 pm, Maxim Yegorushkin <maxim.yegorush ...@gmail.com>
wrote:
>On Nov 10, 12:30 pm, zr <zvir...@gmail. comwrote:
>>Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
There is a way. Disclaimer: it is not blessed by the standard.
>>Vice-versa is easy to do, simply use std::t1::array: :data() and assign
the returned value to the c-style pointer;
if STL does not support this, is there any other library that has such
a container (maybe BOOST)?
Here is an example of what i have in mind:
#include <array>
using namespace std::tr1;
int main()
{
int cArray[] = { 1 , 2, 3, 4};
array<int,4tr 1Array(cArray); // Using some imaginary c-tor. Don't
want to copy. Want to use preallocated memory
Here you do:

// make sure that the binary layouts of
// array<and C-array are the same
typedef int static_assert[sizeof(array<in t,4>) == sizeof(cArray) ?
1 : -1];
// now do the hack
array<int,4>& tr1Array = reinterpret_cas t<array<int,4>& >(cArray);
>>tr1Array[0] = 42;
assert(tr1Arr ay[0] == cArray[0] == 42); // Both point to same memory
tr1Array[100] = 42; //In debug builds, this should raise an exception
cArray[100] = 42; //Much harder to catch
return 0;
}
--
Max

Thanks, Max. I wonder if there is a similar trick for casting a
dynamic array to a std::vector...
Well, yes, by all means. If you don't care about portability, open up
the definition of the 'vector' class, make sure there are no explicit
specialisations for your type, then stuff the data you have into the
struct that has exactly same layout as your 'vector' class, then just
cast the reference to struct to your vector. Just make sure you never
attempt to change the vector, or grow it, or do anything that might
break the fragile state of that Frankenstein monster you're going to put
together. And don't come crying to us when your program doesn't work,
because we won't be able to explain it. It will have *undefined* behaviour.

Come on, give it up and realise that you'll be much better off using the
standard means and worrying about the design at the higher level than
that, and not about the whatever tiny performance improvement you can
squeeze from your program by using such nonsensical approaches. Really.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 10 '08 #5
On Nov 10, 12:30*pm, zr <zvir...@gmail. comwrote:
Hi,

Is there a way to initialize a std::tr1::array with a pre-allocated
built-in array in a copy-less assignment, such that both will point to
the same memory?
Yes, you can use 'placement new':

typedef array <int, 4A;
int init [] = {1, 2, 3, 4};
A& a = *new (init) A;

Of course, this is equivalent to

array <int, 4a = {1, 2, 3, 4};

Regards,
Vidar Hasfjord
Nov 10 '08 #6

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

Similar topics

2
35779
by: Andreas Kuntzagk | last post by:
Hi, There are three ways to (shallow)copy a list l I'm aware of: >>> l2=list(l) >>> l2=l >>> l2.copy.copy(l) Are there any differences? Are there more (reasonable) ways? I think the first is the most pythonic, second looks more like this other
19
4680
by: Claudio Grondi | last post by:
I would like to save time copying the same file (>6 GByte) to various different target storage media connected to the system via USB. Is there a (Python or other) tool able to help me to do this, so that I don't need to copy the source file first to the first media, then to the second, etc.? Claudio
39
2887
by: scooter | last post by:
Given this class heirarchy class Base{}; class A : public Base {}; class B : public Base {};
42
5809
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
15
21202
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including pointers) and for objects types call their default constructor. Any others points i should know?
2
12353
by: Alex | last post by:
Entering the following in the Python shell yields >>> help(dict.copy) Help on method_descriptor: copy(...) D.copy() -> a shallow copy of D >>>
24
3638
by: rdc02271 | last post by:
Hello! Is this too crazy or not? Copy constructor: why can't I copy objects as if they were structs? I have a set of simple objects (no string properties, just integers, doubles) and I have to copy the same object millions of times. So instead of writing in the copy constructor property1=SourceObject.property1 can't I use memory copy functions to do this faster? Is this too stupid? By the way, I'm a C++ newbie! But don't go easy on me...
10
2582
by: utab | last post by:
Dear all, So passing and returning a class object is the time when to include the definition of the copy constructor into the class definition. But if we don't call by value or return by value, we do not need to use the copy-constructor. So depending on the above reasoning I can avoid call by value and return by value for class objects, this bypasses the problem or it seems to me like that. Could any one give me some simple examples...
3
12861
by: maheshkadam | last post by:
Hi friends I am new to perl so please guide me. I have one application which created backup log file every day.But it appends that file so you can see logs for different day in one file only. My requirement is to copy backup log for the specific day (yesterday) and write in other file. That file will be mailed to admin for ready reference. So here is some text from that log file
0
9671
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
10433
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
10212
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10161
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10000
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9035
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...
1
7538
isladogs
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...
0
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4112
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 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.