Coming from writing mostly in Java, I have trouble understanding how to
declare a member without initializing it, and do that later... In Java,
I would write something like
public static void main(String[] args) {
MyType aMember;
...
aMember = new MyType(...)
...
}
However, in C++ this does not seem to work. I declare in class (it's
for serial port communication) like this:
#include <fstream>
#include <boost/thread/thread.hpp>
class COMConn {
public:
COMConn(int port);
~COMConn();
char *send(char);
char *send(char, char[]);
private:
void connect(int);
std::ifstream input;
std::ofstream output;
boost::thread inputthread;
boost::thread outputthread;
};
But when I want to initialize the threads and streams, I want to do
something like
void COMConn::connec t(int port) {
this->input = std::ifstream(" COM1:");
this->inputthread = boost::thread(& input.read); // Not correct, needs
arguments, but skip that for now
//etc for the others
}
How do you go about doing this in C++? I found that I could do
this->input.open("CO M1:");
But that is hardly something that will work in general. I find this
very confusing I must say... Thanks you for any advice
Jul 19 '06
17 2623
Frederick Gotham wrote:
Calle Pettersson posted:
>Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later...
If you want to use a pointer:
int main()
{
MyClass *p;
/* "p" contains garbage right now */
...
p = new MyClass; /* Object created here */
There is simply *no sence* to declare 'p' before this statement.
That Calle has already been told. Just declare/define/initialise
it right where you first use it.
>
...
delete p; /* Object destroyed here */
}
Or perhaps if you wish to pre-allocate the memory:
#include <string>
#include <new>
using std::string;
union Aligned {
void *p;
long a;
long double b;
};
int main()
{
Aligned buf[
sizeof(string) / sizeof(Aligned)
+ !!(sizeof(strin g) % sizeof(Aligned) ) ];
Could you elaborate what this all is for? What are you trying
to accomplish with all that?
>
/* Suff happens... */
string &obj = *::new(&buf) string;
obj.~string();
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
On Wed, 19 Jul 2006 12:11:14 -0400, "Victor Bazarov"
<v.********@com Acast.netwrote:
>Pete Becker wrote:
>Calle Pettersson wrote:
>>Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later... In Java, I would write something like public static void main(String[] args) { MyType aMember; ... aMember = new MyType(...) ... }
The roughly equivalent C++ code would be
MyType *aMember = 0; ... aMember = new MyType(...);
To the OP:
If 'aMember' is a local variable of the 'main' function ("method"), then its name is wrong. It's not really a member, is it?
Moreover, uninitialized variables are nor allowed in Java.
Roland Pibinger wrote:
On Wed, 19 Jul 2006 12:11:14 -0400, "Victor Bazarov"
<v.********@com Acast.netwrote:
Pete Becker wrote:
Calle Pettersson wrote: Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later... In Java, I would write something like public static void main(String[] args) { MyType aMember; ... aMember = new MyType(...) ... }
The roughly equivalent C++ code would be
MyType *aMember = 0;
...
aMember = new MyType(...);
To the OP:
If 'aMember' is a local variable of the 'main' function ("method"), then
its name is wrong. It's not really a member, is it?
Correct, I came up with that method just to show my point, and did so
in an erronus way, which understandably caused some confusion... I'll
try to be more careful in reading my code before posting in the future.
Moreover, uninitialized variables are nor allowed in Java.
Yes they are, as long as you don't try to access them. This will work
just fine:
class MyClass {
public static void main(String[] args) {
MyObject obj;
// blahblahblah
obj = new MyObject();
// etc
}
}
Victor Bazarov posted:
> Aligned buf[ sizeof(string) / sizeof(Aligned) + !!(sizeof(strin g) % sizeof(Aligned) ) ];
Could you elaborate what this all is for? What are you trying
to accomplish with all that?
You can't do the following, because the array might not be aligned properly
to accommodate a particular type:
char buffer[sizeof(T)];
::new(buffer) T;
A possible solution would be to use a union to ensure correct alignment.
(Have you not seen this "trick" before? It's quite common.)
--
Frederick Gotham
Frederick Gotham wrote:
Victor Bazarov posted:
>> Aligned buf[ sizeof(string) / sizeof(Aligned) + !!(sizeof(strin g) % sizeof(Aligned) ) ];
Could you elaborate what this all is for? What are you trying to accomplish with all that?
You can't do the following, because the array might not be aligned
properly to accommodate a particular type:
char buffer[sizeof(T)];
::new(buffer) T;
A possible solution would be to use a union to ensure correct
alignment.
And how using the union you used with a 'void*', a 'long', and
a 'long double' going to accomplish "correct alignment"?
(Have you not seen this "trick" before? It's quite common.)
No, I haven't. Not to say that I've seen all the code in the world,
of course. It does strike me as strange that instead of simply
declaring a local object of type 'std::string' you declare an array
of some weird union type and then use placement new to allocate
a string. And you're saying that it's *quite common*? Indeed...
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Victor Bazarov posted:
And how using the union you used with a 'void*', a 'long', and
a 'long double' going to accomplish "correct alignment"?
Pick the largest integer type.
Pick the largest floating point type.
Pick the largest pointer type.
Put them together and you've got some very strict alignment.
Is it guaranteed to be strict enough? I'm not sure.
Is it likely to be strict enough? Yes, very.
>(Have you not seen this "trick" before? It's quite common.)
No, I haven't. Not to say that I've seen all the code in the world,
of course. It does strike me as strange that instead of simply
declaring a local object of type 'std::string' you declare an array
of some weird union type and then use placement new to allocate
a string. And you're saying that it's *quite common*? Indeed...
Imagine you want to have a local object in a function, but you want some
other function to initialise it:
#include <new>
void OtherFunc(void * const);
int main()
{
char buffer[sizeof(MyType)];
/* Correct alignment not guaranteed */
OtherFunc(buffe r);
}
void OtherFunc(void * const pbuf)
{
/* Do some stuff */
::new(pbuf) MyType();
}
--
Frederick Gotham
Frederick Gotham wrote:
Victor Bazarov posted:
>And how using the union you used with a 'void*', a 'long', and a 'long double' going to accomplish "correct alignment"?
Pick the largest integer type.
Pick the largest floating point type.
Pick the largest pointer type.
What happens to the pointer-to-member type? Did you know their size
is not predetermined? And there is no way to tell which one is the
largest.
Put them together and you've got some very strict alignment.
Yes, but alignment is *always* implementation-defined. Shouldn't we
stop trying to fake implementation-defined behaviour with standard
methods?
Is it guaranteed to be strict enough? I'm not sure.
Exactly.
Is it likely to be strict enough? Yes, very.
Sorry, not good enough.
>>(Have you not seen this "trick" before? It's quite common.)
No, I haven't. Not to say that I've seen all the code in the world, of course. It does strike me as strange that instead of simply declaring a local object of type 'std::string' you declare an array of some weird union type and then use placement new to allocate a string. And you're saying that it's *quite common*? Indeed...
Imagine you want to have a local object in a function, but you want
some other function to initialise it:
#include <new>
void OtherFunc(void * const);
int main()
{
char buffer[sizeof(MyType)];
/* Correct alignment not guaranteed */
OtherFunc(buffe r);
}
void OtherFunc(void * const pbuf)
{
/* Do some stuff */
::new(pbuf) MyType();
}
Don't see it as "common" either. What you ususally see done is
MyType myobject = OtherFunc();
It's not entirely "initialisation " but with optimizations the
compiler is allowed to do, it's *more likely* to be correct, and
therefore *more common*, AFAICT.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: hrmadhu |
last post by:
Hi,
I wish to declare a vector of deque of int, which I do as follows.
#include<vector>
#include<deque>
#include<iostream>
using namespace std;
int main(int argc, char* argv)
{
|
by: ik |
last post by:
Hello All,
I am facing a problem as follows.
I have a header file called myNameSpace.h which as the following
contents.
//Header file .. myNameSpace.h
namespace myNameSpace {
static int iMyInt = 0;
|
by: simondex |
last post by:
Hi, Everyone!
Does anyone know how to initialize an int array with a non-zero number?
Thank You Very Much.
Truly Yours, Simon Dexter
|
by: Felix Kater |
last post by:
Some basic questions about variable initialization:
a. Is it legal to initialize the variables i, b and l like this (see below) ?
b. If so: At what time are they initialized? In other words: how can I
imagine where the compiler puts the code to initialize the variables? Is it done somehow this way that the compiler puts the values of the variables once into memory right as it does with the commands?
c. Are boolean variables exceptions...
|
by: arun |
last post by:
suppose i have a pointer to an array of integers.can i initialize each
member of the array using pointers?plz explain
| |
by: Bill Pursell |
last post by:
I've found myself wanting to do this:
int *x = {1,2,3,4,5};
Obviously, I can't do that. I can certainly non-portably
hack it like int *x = (int *)"\x01\x00\x00\x00\x02\x00...",
but that's the worst idea since W's last one.
Or I can do:
int a = {1,2,3,4,5};
int *x=a;
|
by: Mik0b0 |
last post by:
Hallo.
Let's say, there is a structure
struct struct10{
int a1;
int a2;
int a3;
int a4;
}count={
{10,20,30,40},
{50,60,70,80}
|
by: Reckoner |
last post by:
would it be possible to use one of an object's methods without
initializing the object?
In other words, if I have:
class Test:
def __init__(self):
print 'init'
def foo(self):
print 'foo'
|
by: Jai Prabhu |
last post by:
Hi All,
Consider the following piece of code:
void func (void)
{
static unsigned char arr = "\x00\xAA\xBB";
fprintf (stderr, "0x%x\n", arr);
fprintf (stderr, "0x%x\n", arr);
|
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: 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: 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...
| |