Hi all,
I have a template class (call it Object) whose instances have a
variable size part - an array of of T objects. But this variable size
part is fixed at creation time so instead of allocating two blocks
(one for the object and one for the variable-sized part) one can
allocate a single block via a placement new operator like
template<typena me T>
void* Object<T>::oper ator new(std::size_t sz, std::size_t number) {
return new char[sz + number*sizeof(T )];
}
Creation of Object's goes through factory static methods so these
implementation details are hidden from the client.
I have the following function to get the pointer to the variable part
template<typena me T>
T* Object<T>::getP tr() const {
return (T*)(this + 1);
}
Now the problem is the following: suppose (fixing the parameter type
T) that I derive from Object<T> and also assume that the derived class
adds some instance data. Then am I right in concluding that the above
getPtr returns the wrong answer? And if I am right, how to make sure
that getPtr returns the right pointer for derived classes?
TIA, with my best regards,
G. Rodrigues 8 1550
What you are trying to do is a bad idea.
overload the casting operator to cast any type to any type.
class B
{
};
class A
{
operator B() const;
};
In your case B would the address of the first element of the array.
But a word of caution casting operator is invoked only when you cast a
object (A) to a certain type (B). Not when you cast a object pointer
(A*) to (B)
Raj
Gonçalo Rodrigues wrote: I have a template class (call it Object) whose instances have a variable size part - an array of of T objects. But this variable size part is fixed at creation time so instead of allocating two blocks (one for the object and one for the variable-sized part) one can allocate a single block via a placement new operator like
template<typena me T> void* Object<T>::oper ator new(std::size_t sz, std::size_t number) { return new char[sz + number*sizeof(T )]; }
Creation of Object's goes through factory static methods so these implementation details are hidden from the client.
Who's the client? Did you disable normal construction of your objects?
I have the following function to get the pointer to the variable part
template<typena me T> T* Object<T>::getP tr() const { return (T*)(this + 1); }
Now the problem is the following: suppose (fixing the parameter type T) that I derive from Object<T> and also assume that the derived class adds some instance data. Then am I right in concluding that the above getPtr returns the wrong answer?
I am a bit puzzled by your initial explanation. What's the 'sizeof'
return for your object? And if I derive from your object and define
my own 'operator new', what 'sz' am I going to get?
If you did disable normal construction of your object, how can there be
any derived class?
I can understand that you might want to have the number of 'T' objects
in your 'Object<T>' to be totally dynamic, but pretending that your
object is small but let its allocation function to grab a lot of memory
and screw up all the processing for derived types is not the best way
to manage dynamic allocation.
And if I am right, how to make sure that getPtr returns the right pointer for derived classes?
Allocate the array correctly, dynamically, store a pointer to its first
element and return it. IOW, be normal, be C++.
V
On Mon, 07 Mar 2005 10:45:38 -0500, Victor Bazarov
<v.********@com Acast.net> wrote: Gonçalo Rodrigues wrote: I have a template class (call it Object) whose instances have a variable size part - an array of of T objects. But this variable size part is fixed at creation time so instead of allocating two blocks (one for the object and one for the variable-sized part) one can allocate a single block via a placement new operator like
template<typena me T> void* Object<T>::oper ator new(std::size_t sz, std::size_t number) { return new char[sz + number*sizeof(T )]; }
Creation of Object's goes through factory static methods so these implementation details are hidden from the client. Who's the client? Did you disable normal construction of your objects?
I have the following function to get the pointer to the variable part
template<typena me T> T* Object<T>::getP tr() const { return (T*)(this + 1); }
Now the problem is the following: suppose (fixing the parameter type T) that I derive from Object<T> and also assume that the derived class adds some instance data. Then am I right in concluding that the above getPtr returns the wrong answer?
I am a bit puzzled by your initial explanation. What's the 'sizeof' return for your object? And if I derive from your object and define my own 'operator new', what 'sz' am I going to get?
Hmm, rereading my explanation I just noticed I left out some important
details.
Let me try to explain myself a little bit better: Object<T> instances
are roughly of the form
template<typena me T>
class Object {
private:
//Number of T objects (usually small <= 8).
std::size_t number;
//Pointer to array of T objects.
T* ptr;
//Some more data.
...
}
An initial analysis showed that a lot of instances of Object<T> will
be created and destroyed during a run of the program. Having a little
bit of free time (and out of boredom) I started hashing out a scheme
to make creation/destruction of objects a little more efficient.
As I said Object<T> instances are immutable, once created they never
change. Creation of Object<T> instances goes through a factory static
method; constructors are protected so that all clients (except derived
classes) have to go through the factory function.
One possible optimization is to allocate the Object and the array in a
single block (instead of two blocks, one for the Object and another
for the array) via a placement new operator with the array being
placed right next to the Object.
Now comes what I left out: Since the array is next to the Object,
another possible optimization, is getting rid of the T* ptr and
calculate the address of the array as an offset
template<typena me T>
virtual T* Object<T>::getP tr() const {
return (T*)(this + 1);
}
IOW if you an Object<T>* pointer ptr to a derived class (assume it has
some more instance data) instance, does getPtr return the right
address?
If you did disable normal construction of your object, how can there be any derived class?
I can understand that you might want to have the number of 'T' objects in your 'Object<T>' to be totally dynamic, but pretending that your object is small but let its allocation function to grab a lot of memory and screw up all the processing for derived types is not the best way to manage dynamic allocation.
And if I am right, how to make sure that getPtr returns the right pointer for derived classes?
Allocate the array correctly, dynamically, store a pointer to its first element and return it. IOW, be normal, be C++.
Be normal :-) good advice - I will follow it. View the above as a
curiosity question.
TIA, best regards,
G. Rodrigues
Gonçalo Rodrigues wrote: [...] Be normal :-) good advice - I will follow it. View the above as a curiosity question.
I just couldn't imagine how you could have a dynamically sized object
using the 'new' trick and at the same time inherit from that object,
which requires a constant size of the class object.
V
Gonçalo Rodrigues schrieb: template<typena me T> class Object { private: //Number of T objects (usually small <= 8). std::size_t number; //Pointer to array of T objects. T* ptr; //Some more data. ... }
if I understand your explanation correctly, what you want is something
like this:
template<typena me T>
struct ObjectBase{
//pure virtual accessor functions to moreData
};
template<typena me T,unsigned int i>
struct Object : ObjectBase<T>{
T moreData[i];
//virtual accessor functions to moreData
};
On Wed, 09 Mar 2005 01:29:28 +0100, Stefan Strasser
<ss*******@syst emhaus-gruppe.de> wrote: Gonçalo Rodrigues schrieb: template<typena me T> class Object { private: //Number of T objects (usually small <= 8). std::size_t number; //Pointer to array of T objects. T* ptr; //Some more data. ... }
if I understand your explanation correctly, what you want is something like this:
template<typen ame T> struct ObjectBase{ //pure virtual accessor functions to moreData };
template<typen ame T,unsigned int i> struct Object : ObjectBase<T>{ T moreData[i]; //virtual accessor functions to moreData };
Heh, I'm not very good at explaining things, am I? :-)
Boiling down, it resumes to: since sizeof is a compile time operator,
if I have a pointer
Base* ptr = & of some Derived object
sizeof(*ptr) returns the size of the static type (is this the correct
wording?) of the pointed to object, that is, sizof(Base), not the size
of the dynamic type, that is, sizeof(Derived) . So the question is: is
it possible to calculate the "dynamic size"?
Just a curiosity question.
Regards,
G. Rodrigues
P:S: My appologies for not being very good at explaining myself.
"Gonçalo Rodrigues" wrote:
Boiling down, it resumes to: since sizeof is a compile time operator, if I have a pointer
Base* ptr = & of some Derived object
sizeof(*ptr) returns the size of the static type (is this the correct wording?)
Yep.
of the pointed to object, that is, sizof(Base), not the size of the dynamic type, that is, sizeof(Derived) .
Yep.
So the question is: is it possible to calculate the "dynamic size"?
AFAIK No.
--
Karl Heinz Buchegger kb******@gascad .at
Gonçalo Rodrigues schrieb: if I understand your explanation correctly, what you want is something like this:
template<type name T> struct ObjectBase{ //pure virtual accessor functions to moreData };
template<type name T,unsigned int i> struct Object : ObjectBase<T>{ T moreData[i]; //virtual accessor functions to moreData };
So the question is: is it possible to calculate the "dynamic size"?
no, but you can implement a virtual function for that.
it looked to me like you want to get the "dynamic size" of your object
to be able to store some other data associated with the object behind
it. and this is what my example does. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Victor Hannak |
last post by:
I have two classes derived from a base class. The two derived classes each
utilize a structure that is slightly different from one another. i.e.
DerivedClass1:
struct NodeStruct {
float NodeValue;
ListStruct *NextNode;
}
|
by: Art |
last post by:
This is partially an academic question, but I'm trying to understand
templates better. I have a base class that uses template parameters to
define the behavior of its class. I want to subclass this to extend
the behavior. I also want to contain pointers to derived classes
somehow, in a vector, say.
My question is: How do I assign derived classes to the base class?
Here is an example:
|
by: Shao Zhang |
last post by:
Hi,
I am not sure if the virtual keyword for the derived classes are
required given
that the base class already declares it virtual.
class A
{
public:
virtual ~A();
|
by: J.J. Feminella |
last post by:
(Please disregard the previous message; I accidentally sent it before it was
completed.)
I have source code similar to the following.
public class Vehicle
{
protected string dataV;
// ... more protected fields
}
|
by: Mark McDonald |
last post by:
This question kind of follows on from Mike Spass’ posting 10/11/2004; I don’t
understand why you can’t declare an implicit operator to convert a base class
to a derived class.
The text books say “neither the source nor the target types of a conversion
can be a base type of the other, since a conversion would then already
existâ€. But this is not really true, whilst automatic (implicit) conversions
do occur from the derived...
| |
by: John Glover |
last post by:
I'm having a very strange problem with XML serialization. I'm writing web
services which pass instances of various classes back and forth as parameters
and return values of web methods. The problem is that in my derived classes,
the XML that is automatically generated is lacking the properties of the base
class. For example:
public class MyBaseClass {
public MyBaseClass ( ) { }
private string myVariable;
|
by: Jordan Taylor |
last post by:
Hi, can anyone suggest how the compiler will decide which bar() to
invoke when we call d.dio()? I am getting the following output:
B foo
B bar
but is there a situation when the same code can print
B foo
D bar
|
by: desktop |
last post by:
On this page:
http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html
Shape specify the virtual function:
virtual double Intersect( const Shape& s) = 0;
then the derived class Circle also specify:
|
by: Bob Johnson |
last post by:
I have a base class that must have a member variable populated by, and only
by, derived classes.
It appears that if I declare the variable as "internal protected" then the
base class *can* populate the variable, but the population is not *required*
by the derived class (which must be the case).
What would meet the requirements is if I create an abstract method in the
base class that populates the member variable. In this case the...
|
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...
|
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: 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,...
|
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...
|
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: 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();...
|
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: 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...
| |