Using new (this) to reuse constructors
Posted
by Brandon Bodnar
on Stack Overflow
See other posts from Stack Overflow
or by Brandon Bodnar
Published on 2010-03-22T20:30:01Z
Indexed on
2010/03/22
20:31 UTC
Read the original article
Hit count: 175
c++
This came up recently in a class for which I am a teaching assistant. We were teaching the students how to do copy constructors in c++, and the students who were originally taught java asked if you can call one constructor from another. I know the answer to this is no, as they are using the pedantic flag for their code in class, and the old standards do not have support for this. I found on Stackoverflow and other sites a suggestion to fake this using new (this)
such as follows
class MyClass
{
private:
int * storedValue;
public:
MyClass(int initialValue = 0)
{
storedValue = new int(initialValue);
}
~ MyClass()
{
delete storedValue;
}
MyClass(const MyClass &b)
{
new (this) MyClass(*(b.storedValue));
}
int value() {
return *storedValue;
}
};
This is really simple code, and obviously does not save any code by reusing the constructor, but it is just for example.
My question is if this is even standard compliant, and if there are any edge cases that should be considered that would prevent this from being sound code?
© Stack Overflow or respective owner