How to check if an object construction is complete? - c++

Have a class with couple of integers and a pointer ,
class A {
int a;
int b;
char* s;
public:
...
class ConstructA {
A &a;
public:
ConstructA (A& ta) : a(ta) {}
...
};
};
As seen ConstructA is responsible for constructing object A.
I want to write a method to see if ConstructA was successful in constructing the object a. How would you go about it ?

Since there is no way for a constructor to fail in C++, an object either:
does not exist
is successfully constructed.
If a constructor throws an exception, the object effectively does not exist at the point the exception is caught.
You may want to implement an additional method such as isOK() that returns whether or not the internal state of the object represents something useful. For example, if you have an object that represents a file, then you could use isOK() to indicate that the file could be successfully opened. However, as far as C++ is concerned, the file object would be fully constructed whether or not the file could be opened.
Having said that, I'm not entirely sure what the role of the ConstructA class is in your example.

As a general rule, if there is any failure in construction you will get an exception thrown -- either a program-specific exception from the object itself, or else a memory exception or something similar from the runtime.
In this particular case, you are not constructing an object of type A, you are initializing a reference. So there is no construction that has an opportunity to fail.
(Perhaps a little more detail about what you are trying to accomplish would help somebody give a better answer?)

You're ConstructA is just trying to hold on to a reference of an already constructed A, try changing it to this:
class ConstructA {
A a; // Don't make this a reference
public:
ConstructA (A& ta) : a(ta) {}
...
};

First, your ConstructA class makes no sense at all to me. There really are two cases basically:
The construction of an object fails
The object is left in an defined, but restricted state. Strictly, the construction succeeded, but possibly not the the degree that the caller wished. He can optionally later complete the construction.
1. The construction fails
I'll use your ConstructA in the following code just to make the point of signaling about construction failure:
A a0;
try {
A::ConstructA a1(a0);
} catch(...) {
// fail to construct a1
}
Constructors throw exceptions to signal when their constructions fail. The idea is that if construction of an object fails, then the object is not constructed. In other words, the object does not exist. If you have to initialize a1 in an constructor init list, there is a way too:
struct B {
B() try : a1(a0) {
// other constructor code...
} catch(...) {
// fail to construct either a0 or a1, or constructor
// code threw
}
A a0;
A::ConstructA a1;
};
try {
B b;
} catch(...) {
// fail to construct B
}
First, code in the catch block of the constructor is executed, then the exception is automatically propagated to the code that created the B object, and its catch blocks are considered.
Your class ConstructA's constructor could look like this, for example:
struct ConstructA {
ConstructA(A &a):a(a) {
if(!condition_met) {
throw std::runtime_error("condition_met false");
}
}
A &a;
};
2. The object is in a restricted state
That is exactly the case what you have when you have a file stream object, but which is not connected to a file. If in the constructor you find that the file mentioned doesn't exist, you can still fully construct the stream, but set it in a not-opened state. Some operations could be disallowed then and you can have a isOpen or isValid function that you can use to query the state of the object.
This can be applied to other cases too. Some framework i used has a Color class. Default constructing a color class left it in a invalid state, so that it doesn't compare equal to any valid color:
Color c;
assert(c.isValid() == false);
The same technique is used for a null pointer. It's set to a defined, but restricted state when you assign NULL to it:
int *a = NULL;
assert(a == NULL);
You cannot dereference a null pointer for example.

mkal, I always suggest people not to use exception in C++. It cause more problems that it tries to solve.
To answer your question, to avoid exception in C++, you probably can reduce the work you
want to do in your constructor, and create an init() method instead, that returns the error-code if something goes wrong.
Basically, whatever you do in C++ Constructor, it has to succeed.
Hope that helps.

Related

call another constructor from constructor body

I have an object that has different constructors. Now I want to add another constructor that based on arbitrary data will try to process that data and call the correct constructor.
AFAIK there are two ways to do it:
static function that returns the created object
static *A from_data(/arbitrary data/);
create a private "init" function that is called by constructors
But I am wondering what are the problems and potential pitfalls of using a placement new on this using the desired constructor. So the code would be:
#include <new>
struct A
{
/*different constructors*/
A(int i) {};
A(double d) {};
A(/*large set of data*/)
{
/*large set of data gets processed and depending on the processing a different constructor gets called*/
this->~A(); //deletes current object
if (true) {
new (this) A(1); //reconstructs object calling the correct constructor for the data
} else {
new (this) A(1.0); //reconstructs object calling the correct constructor for the data
}
};
};
int main(int argc, char* argv[])
{
A a;
}
You want a compile time decision (choice of constructor to delegate to) from run-time information (result of processing a data set).
That means that what you directly want, cannot be done.
But you can use your idea of a static member function that returns the created object, except that instead of A* it should return A, or else a smart pointer.
Re the other suggested solution,
” create a private "init" function that is called by cosntructors
… that doesn't solve the stated problem, and it's a generally bad idea.
Re
” what are the problems and potential pitfalls of using a placement new on this
Well, it's not code you can rely on. I believe it's Undefined Behavior because at the point where the object self-destroys it's not completely initialized. If it should turn out that it's technically well defined for the case at hand, it's not code that you would want to rely on. And in a setting with possible maintenance, someone stumbling on this code would have to replace it rather than wasting time trying to prove UB or not. Just Say No™ to the dark corners of the language.
I briefly considered spending some time trying to figure out whether the shown example results in undefined behavior, or not. But I quickly decided that this is irrelevant, a waste of time, and is completely beside the point because the current C++ standard has a perfectly well-defined, clean mechanism to do exactly the same thing, and it would be more productive to focus my answer on that, instead.
I'm referring to delegating constructors, of course:
class A {
public:
A(int n) {
// whatever
}
A(const char *p, double z)
: A( /* some formula that calculates an int value goes here */ )
{
}
};
The current C++ standard specifies a well-defined way for one constructor to delegate the actual job of constructing and initializing an instance of the class by invoking a different constructor.
Note that this doesn't mean that one constructor gets to execute arbitrary code, before deciding to invoke the delegated-to constructor. The delegation must occur as the very first order of business, where you normally see the initialization section of a constructor; where you see things like the superclasses' constructors, if any.
Only after the delegated-to constructor returns, does the delegated-from constructor have an option of running more code of its own, to finish the job.
But this is just a minor inconvenience, easily addressed with just a little bit of coding:
class A {
public:
A(int n) {
// whatever
}
A(const char *p, double z)
: A(figure_out_an_int_value_from_p_and_z(p, z))
{
}
private:
static int figure_out_an_int_value_from_p_and_z(const char *p, double z)
{
int a_very_complicated_value;
// Some complicated code that computes a_very_complicated_value.
return a_very_complicated_value;
}
};

Calling a constructor of the base class from a subclass' constructor body

I was under impression that it's impossible, see for example:
Calling the constructor of the base class after some other instructions in C++
But the following program runs and produces two lines of "Constructor Person":
#include <iostream>
class Person
{
public:
Person()
{
std::cout << "Constructor Person" << std::endl; }
};
class Child : public Person
{
public:
Child()
{
c = 1;
Person();
}
int c;
};
int main()
{
Child child;
return 0;
}
The first one is implicit call of the default constructor, that's clear. What about the 2nd one - does it mean that the action described in the title is legitimate? I use Visual C++ 2010.
The call inside the child class constructor is not calling the base class constructor, it is creating a temporary, unnamed and new object of type Person. It will be destroyed as the constructor exits. To clarify, your example is the same as doing this:
Child() { c = 1; Person tempPerson; }
Except in this case, the temporary object has a name.
You can see what I mean if you modify your example a little:
class Person
{
public:
Person(int id):id(id) { std::cout << "Constructor Person " << id << std::endl; }
~Person(){ std::cout << "Destroying Person " << id << std::endl; }
int id;
};
class Child : public Person
{
public:
Child():Person(1) { c = 1; Person(2); }
int c;
};
int main() {
Child child;
Person(3);
return 0;
}
This produces the output:
Constructor Person 1
Constructor Person 2
Destroying Person 2
Constructor Person 3
Destroying Person 3
Destroying Person 1
The following is an excerpt from "Accelerated C++":
"Derived objects are constructed by:
1. Allocating space for the entire object (base class members as well as derived class members);
2. Calling the base-class constructor to initialize the base-class part of the object;
3. Initializing the members of the derived class as directed by the constructor initializer;
4. Executing the body of the derived-class constructor, if any."
Summarizing the answers and comments: Calling a constructor of the base class from a subclass' constructor body is impossible in the sense that #2 above must precede #4.
But we still can create a base object in the derived constructor body thus calling a base constructor. It will be an object different from the object being constructed with the currently executed derived constructor.
You can't call it from the body of the child constructor, but you can put it into the initializer list:
public:
Child() : Person() { c = 1; }
Of course it's not helpful to call the default constructor of the parent because that will happen automatically. It's more useful if you need to pass a parameter to the constructor.
The reason you can't call the constructor from the body is because C++ guarantees the parent will be finished constructing before the child constructor starts.
The answers to this question while usually technically true and useful, don't give the big picture. And the big picture is somewhat different than it may seem :)
The base class's constructor is always invoked, otherwise in the body of the derived class's constructor you'd have a partially constructed and thus unusable object. You have the option of providing arguments to the base class constructor. This doesn't "invoke" it: it gets invoked no matter what, you can just pass some extra arguments to it:
// Correct but useless the BaseClass constructor is invoked anyway
DerivedClass::DerivedClass() : BaseClass() { ... }
// A way of giving arguments to the BaseClass constructor
DerivedClass::DerivedClass() : BaseClass(42) { ... }
The C++ syntax to explicitly invoke a constructor has a weird name and lives up to this name, because it's something that's very rarely done - usually only in library/foundation code. It's called placement new, and no, it has nothing to do with memory allocation - this is the weird syntax to invoke constructors explicitly in C++:
// This code will compile but has undefined behavior
// Do NOT do this
// This is not a valid C++ program even though the compiler accepts it!
DerivedClass::DerivedClass() { new (this) BaseClass(); /* WRONG */ }
DerivedClass::DerivedClass() { new (this) BaseClass(42); /* WRONG */ }
// The above is how constructor calls are actually written in C++.
So, in your question, this is what you meant to ask about, but didn't know :) I imagine that this weird syntax is helpful since if it were easy, then people coming from languages where such constructor calls are commonplace (e.g. Pascal/Delphi) could write lots of seemingly working code that would be totally broken in all sorts of ways. Undefined behavior is not a guarantee of a crash, that's the problem. Superficial/obvious UB often results in crashes (like null pointer access), but a whole lot of UB is a silent killer. So making it harder to write incorrect code by making some syntax obscure is a desirable trait in a language.
The "second option" in the question has nothing to do with constructor "calls". The C++ syntax of creating a default-constructed instance of a value of BaseClass object is:
// Constructs a temporary instance of the object, and promptly
// destructs it. It's useless.
BaseClass();
// Here's how the compiler can interpret the above code. You can write either
// one and it has identical effects. Notice how the scope of the value ends
// and you have no access to it.
{
BaseClass __temporary{};
}
In C++ the notion of a construction of an object instance is all-permeating: you do it all the time, since the language semantics equate the existence of an object with that object having been constructed. So you can also write:
// Constructs a temporary integer, and promptly destructs it.
int();
Objects of integer type are also constructed and destructed - but the constructor and destructor are trivial and thus there's no overhead.
Note that construction and destruction of an object this way doesn't imply any heap allocations. If the compiler decides that an instance has to be actually materialized (e.g. due to observable side effects of construction or destruction), the instance is a temporary object, just like the temporaries created during expression evaluation - a-ha, we notice that type() is an expression!
So, in your case, that Person(); statement was a no-op. In code compiled in release mode, no machine instructions are generated for it, because there's no way to observe the effects of this statement (in the case of the particular Person class), and thus if no one is there to hear the tree fall, then the tree doesn't need to exist in the first place. That's how C++ compilers optimize stuff: they do lot of work to prove (formally, in a mathematical sense) whether the effects of any piece of code may be unobservable, and if so the code is treated as dead code and removed.
Yeah, I know this is a year old but I found a way to do it. This may not be the best practice. For example, destroying the base class instance from within the derived class constructor sounds like a recipe for disaster. You could skip the destructor step, but that may lead to a memory leak if the base class constructor does any allocation.
class Derived : public Base
{
public:
Derived()
{
// By the time we arrive here, the base class is instantiated plus
// enough memory has been allocated for the additional derived class stuff.
// You can initialize derived class stuff here
this->Base::~Base(); // destroy the base class
new (this) Base(); // overwrites the base class storage with a new instance
}
};

Is there a potential for resource leak/double free here?

The following sample (not compiled so I won't vouch for syntax) pulls two resources from resource pools (not allocated with new), then "binds" them together with MyClass for the duration of a certain transaction.
The transaction, implemented here by myFunc, attempts to protect against leakage of these resources by tracking their "ownership". The local resource pointers are cleared when its obvious that instantiation of MyClass was successful. The local catch, as well as the destructor ~MyClass return the resources to their pool (double-frees are protected by teh above mentioned clearing of the local pointers).
Instantiation of MyClass can fail and result in an exception at two steps (1) actual memory allocation, or (2) at the constructor body itself. I do not have a problem with #1, but in the case of #2, if the exception is thrown AFTER m_resA & m_resB were set. Causing both the ~MyClass and the cleanup code of myFunc to assume responsibility for returning these resources to their pools.
Is this a reasonable concern?
Options I have considered, but didn't like:
Smart pointers (like boost's shared_ptr). I didn't see how to apply to a resource pool (aside for wrapping in yet another instance).
Allowing double-free to occur at this level but protecting at the resource pools.
Trying to use the exception type - trying to deduce that if bad_alloc was caught that MyClass did not take ownership. This will require a try-catch in the constructor to make sure that any allocation failures in ABC() ...more code here... wont be confused with failures to allocate MyClass.
Is there a clean, simple solution that I have overlooked?
class SomeExtResourceA;
class SomeExtResourceB;
class MyClass {
private:
// These resources come out of a resource pool not allocated with "new" for each use by MyClass
SomeResourceA* m_resA;
SomeResourceB* m_resB;
public:
MyClass(SomeResourceA* resA, SomeResourceB* resB):
m_resA(resA), m_resB(resB)
{
ABC(); // ... more code here, could throw exceptions
}
~MyClass(){
if(m_resA){
m_resA->Release();
}
if(m_resB){
m_resB->Release();
}
}
};
void myFunc(void)
{
SomeResourceA* resA = NULL;
SomeResourceB* resB = NULL;
MyClass* pMyInst = NULL;
try {
resA = g_pPoolA->Allocate();
resB = g_pPoolB->Allocate();
pMyInst = new MyClass(resA,resB);
resA=NULL; // ''ownership succesfully transfered to pMyInst
resB=NULL; // ''ownership succesfully transfered to pMyInst
// Do some work with pMyInst;
...;
delete pMyInst;
} catch (...) {
// cleanup
// need to check if resA, or resB were allocated prior
// to construction of pMyInst.
if(resA) resA->Release();
if(resB) resB->Release();
delete pMyInst;
throw; // rethrow caught exception
}
}
Here is your chance for a double call to release:
void func()
{
MyClass a(resourceA, resourceB);
MyClass b(a);
}
Whoops.
If you use an RIAA wrapper fro your resources you will be much less likely to make mistakes. Doing it this way is error prone. You are currently missing the copy constructor and assignment operator on MyClass that could potentially lead to a double call to Release() as shown above.
Because of the complexity of handling resource a class should only own one resource. If you have multiple resource delegate their ownership to a class that it dedicated to their ownership and use multiple of these objects in your class.
Edit 1
Lut us make some assumptions:
Resources are shared and counted. You increment the count with Acquire() and decrement the count with Release(). When count reaches zero they are automatically destroyed.
class ReferenceRapper
{
ReferenceBase* ref;
public:
ReferenceWrapper(ReferenceBase* r) : ref (r) {/* Pool set the initial count to 1 */ }
~ReferenceWrapper() { if (ref) { ref->Release();} }
/*
* Copy constructor provides strong exception guarantee (aka transactional guarantee)
* Either the copy works or both objects remain unchanged.
*
* As the assignment operator is implemented using copy/swap it also provides
* the strong exception guarantee.
*/
ReferenceWrapper(ReferenceWrapper& copy)
{
if (copy.ref) {copy.ref->Acquire();}
try
{
if (ref) {ref->Release();}
}
catch(...)
{
if (copy.ref)
{ copy.ref->Release(); // old->Release() threw an exception.
// Must reset copy back to its original state.
}
throw;
}
ref = copy.ref;
}
/*
* Note using the copy and swap idium.
* Note: To enable NRVO optimization we pass by value to make a copy of the RHS.
* rather than doing a manual copy inside the method.
*/
ReferenceWrapper& operator(ReferenceWrapper rhsCopy)
{
this->swap(rhsCopy);
}
void swap(ReferenceWrapper& rhs) throws ()
{
std::swap(ref, rhs.ref);
}
// Add appropriate access methods like operator->()
};
Now that the hard work has been done (managing resources). The real code becomes trivial to write.
class MyClass
{
ReferenceWrapper<SomeResourceA> m_resA;
ReferenceWrapper<SomeResourceB> m_resB;
public:
MyClass(ReferenceWrapper<SomeResourceA>& a, ReferenceWrapper<SomeResourceB>& b)
: m_resA(a)
, m_resB(b)
{
ABC();
}
};
void myFunc(void)
{
ReferenceWrapper<SomeResourceA> resA(g_pPoolA->Allocate());
ReferenceWrapper<SomeResourceB> resB(g_pPoolB->Allocate());
std::auto_ptr<MyClass> pMyInst = new MyClass(resA, resB);
// Do some work with pMyInst;
}
Edit 2 Based on comment below that resources only have one owner:
If we assume a resource has only one owner and is not shared then it becomes trivial:
Drop the Release() method and do all the work in the destructor.
Change the Pool methods so that the construct the pointer into a std::auto_ptr and return the std::auto_ptr.
Code:
class MyClass
{
std::auto_ptr<SomeResourceA> m_resA;
std::auto_ptr<SomeResourceB> m_resB;
public:
MyClass(std::auto_ptr<SomeResourceA>& a, std::auto_ptr<SomeResourceB>& b)
: m_resA(a)
, m_resB(b)
{
ABC();
}
};
void myFunc(void)
{
std::auto_ptr<SomeResourceA> resA(g_pPoolA->Allocate());
std::auto_ptr<SomeResourceB> resB(g_pPoolB->Allocate());
std::auto_ptr<MyClass> pMyInst = new MyClass(resA, resB);
// Do some work with pMyInst;
}
I don't see any leak in this small code.
If the constructor throws exception, then the destructor would not be called, since the object never existed. Hence I don't see double-delete either!
From this article by Herb Sutter :Constructor Exceptions in C++, C#, and Java:
constructor conceptually turns a
suitably sized chunk of raw memory
into an object that obeys its
invariants. An object’s lifetime
doesn’t begin until its constructor
completes successfully. If a
constructor ends by throwing an
exception, that means it never
finished creating the object and
setting up its invariants — and at
the point the exceptional constructor
exits, the object not only doesn’t
exist, but never existed.
A destructor/disposer conceptually
turns an object back into raw memory.
Therefore, just like all other
nonprivate methods,
destructors/disposers assume as a
precondition that “this” object is
actually a valid object and that its
invariants hold. Hence,
destructors/disposers only run on
successfully constructed objects.
I think this should clear your doubts!
Your code is fine. But to make it even better, use some kind of smart-pointer!
Edit: for example you can use shared_ptr:
class SomeExtResourceA;
class SomeExtResourceB;
class MyClass {
private:
// These resources come out of a resource pool not allocated with "new" for each use by MyClass
shared_ptr<SomeResourceA> m_resA;
shared_ptr<SomeResourceB> m_resB;
public:
MyClass(const shared_ptr<SomeResourceA> &resA, const shared_ptr<SomeResourceB> &resB):
m_resA(resA), m_resB(resB)
{
ABC(); // ... more code here, could throw exceptions
}
}
};
void myFunc(void)
{
shared_ptr<SomeResourceA> resA(g_pPoolA->Allocate(), bind(&SomeResourceA::Release, _1));
shared_ptr<SomeResourceB> resB(g_pPoolB->Allocate(), bind(&SomeResourceB::Release, _1));
MyClass pMyInst(resA,resB);
// you can reset them here if you want, but it's not necessery:
resA.reset(), resB.reset();
// use pMyInst
}
I find this solution with RAII much simpler.
Just put if (pMyInst) { ... } around release/delete code in your catch and you are fine.
The classic usage to explicitly take ownership is the std::auto_ptr
Something like this:
std::auto_ptr<SomeResourceA>(g_pPoolA->Allocate()) resA;
std::auto_ptr<SomeResourceB>(g_pPoolB->Allocate()) resB;
pMyInst = new MyClass(resA.release(),resB.release());
You transfer the ownership when you call the constructor.

How to Detect Stack Unwinding in a Destructor

I have a simple C++ object that I create at the start of function F() to ensure two matched functions (OpDo, OpUndo) are called at the start and return of the F(), by using the object's constructor and destructor. However, I don't want the operation to be undone in case an exception was thrown within the body of F(). Is this possible to do cleanly? I have read about std::uncaught-exception, but its use does not seem to be recommended.
Most people have used std::uncaught_exception() to try to tell if an exception is pending, so they can throw an exception from a destructor if there isn't one already. That is generally considered Not A Good Idea.
If you want to not undo an operation if an exception has thrown, it should do the trick.
Remember that the destructor is your last chance to release any resources an object has, because after the destructor ends the object does not exist, and any resources it held are now permanently leaked. If OpDo() allocates any memory or file handles or whatever, you do need to deal with that in the destructor no matter what.
You can subvert the Scope Guard idiom. Instead of not doing something in the destructor when no exception is thrown, we invert that and only do something if no exception is thrown:
class DoUndoRAII{
public:
DoUndoRAII()
: noexcept_(false)
{
// your stuff here
}
~DoUndoRAII(){
if(noexcept_){
// do whatever you need to do
}
}
void no_exception(){
noexcept_ = true;
}
private:
bool noexcept_;
};
void func(){
DoUndoRAII do_undo;
// last line
do_undo.no_exception();
}
When an exception is thrown, do_undo.no_exception() will never be called and thus never set the noexcept_ value to true. :) An example can be found here on Ideone.
Let's assume that your F returns some class Helper:
Helper F()
{
MyClass doUndoWrapper;
}
When flow is normal - Helper is created. When exception is raised no copy of Helper is created. Try use this semantic by placing to private region constructor of Helper and declaring F as friend - so no one could create helper.
class Helper
{
private:
friend Helper F();
Helper(){ //place there OpDo semantic - first entry
// construct this class
Helper(const Helper& copy){ //this must present to allow stack operations
// copy constructor will be called at end of `F` to return value
// so place OpUndo semantic there to mark success without exception

Calling a constructor to reinitialize variables doesn't seem to work?

I wanted to run 1,000 iterations of a program, so set a counter for 1000 in main. I needed to reinitialize various variables after each iteration, and since the class constructor had all the initializations already written out - I decided to call that after each iteration, with the result of each iteration being stored in a variable in main.
However, when I called the constructor, it had no effect...it took me a while to figure out - but it didn't reinitialize anything!
I created a function exactly like the constructor - so the object would have its own version. When I called that, it reinitialized everything as I expected.
int main()
{
Class MyClass()
int counter = 0;
while ( counter < 1000 )
{ stuff happens }
Class(); // This is how I tried to call the constructor initially.
// After doing some reading here, I tried:
// Class::Class();
// - but that didn't work either
/* Later I used...
MyClass.function_like_my_constructor; // this worked perfectly
*/
}
...Could someone try to explain why what I did was wrong, or didn't work, or was silly or what have you? I mean - mentally, I just figured - crap, I can call this constructor and have all this stuff reinitialized. Are constructors (ideally) ONLY called when an object is created?
Your line Class(); does call the constructor of the class Class, but it calls it in order to create a "temporary object". Since you don't use that temporary object, the line has no useful effect.
Temporary objects (usually) disappear at the end of the expression in which they appear. They're useful for passing as function parameters, or initializing other objects. It's almost never useful to just create one in a statement alone. The language allows it as a valid expression, it's just that for most classes it doesn't do very much.
There is no way in C++ to call a constructor on an object which has already been constructed. The lifecycle of a C++ object is one construction, and one destruction. That's just how it works. If you want to reset an object during its life, you've done the right thing, which is to call a function to reset it. Depending on your class you might not need to write one - the default assignment operator might do exactly what you need. That's when a temporary can come in handy:
Class myObject;
// ... do some stuff to myObject ...
myObject = Class();
This updates myObject with the values from the freshly-constructed temporary. It's not necessarily the most efficient possible code, since it creates a temporary, then copies, then destroys the temporary, rather than just setting the fields to their initial values. But unless your class is huge, it's unlikely that doing all that 1000 times will take a noticeable amount of time.
Another option is just to use a brand new object for each iteration:
int main() {
int counter = 0;
while (counter < 1000) {
Class myObject;
// stuff happens, each iteration has a brand new object
}
}
Note that Class MyClass(); does not define an object of type Class, called MyClass, and construct it with no parameters. It declares a function called MyClass, which takes no parameters and which returns an object of type Class. Presumably in your real code, the constructor has one or more parameters.
What happens in that line reading...
Class ();
Is that you do in fact call the constructor - for a temporary object that is being constructed from scratch, and which is then immediately destructed since you're not doing anything with it. It's very much like casting to Class, which creates a value using a constructor call, except that in this case there's no value to cast so the default constructor is used.
It's possible that the compiler then optimises this temporary away, so there's no constructor at all - I'm not sure whether that's allowed or not.
If you want to re-initialise members, calling the constructor isn't the way to do it. Move all your initialisation code into another method and call that from your constructor, and when you want to re-initialise, instead.
Yes, this not typical usage. Create a function that resets your variables, and call the method whenever you need it.
You fell prey to a common misreading of c++. The new c++0x makes things a bit clearer.
The problem is constructions syntax looks like a function call.
void foo( int i ) { }
class Foo { };
Foo(10); // construct a temporary object of type foo
foo(10); // call function foo
Foo{10}; // construct a temporary object of type foo in c++0x syntax
I think the c++0x syntax is more clear.
You could do what you want with this syntax. But beware it is very advanced and you should not do it.
MyClass.~Class(); // destruct MyClass
new( &MyClass ) Class;
With such requirements, I generally write a clear() (public) method. I call it from constructor, destructor. User code can call it whenever it wants to.
class Foo
{
public:
Foo() { clear(); }
~Foo() { clear(); }
void clear(); // (re)initialize the private members
private:
// private members
};
To answer the question here, the clear() method may be called whenever it is required to re-initialize the class as it was just after the initial construction.