I have spent a great deal of time programming in Java and a decent amount of time writing c++, but I have run into an issue I haven't been able to solve. In a Java class I can simply write the following,
public void doOperation(object a)
{
if(a != this)
{
set(a); // just some method that sets this.a = object.a
}
doOperation();
}
public void doOperation()
{
this.a = pow(this.a,3);
}
The part I am having trouble implementing in c++ is the if statement where I check if the argument object is equal to this. I have tried this in c++
object::doOperation(object a)
{
if(a != this)
{
set(a);
}
doOperation();
}
object::doOperation()
{
this->a = pow(this->a,3)
}
The error I get reads, "no match for ‘operator!=’ (operand types are ‘object’ and ‘object* const’)". Thanks in advance for anybody who can help!
You can simply pass "a" by reference, take a pointer to "a" and compare it with "this", like so:
object::doOperation(object & a)
{
if(&a != this)
{
set(a);
}
doOperation();
}
object::doOperation()
{
this->a = pow(this->a,3)
}
This is a standard way that people would e.g. implement copy assignment operators in C++. It's not always done this way, but often the implementation of that will take a const reference to an object, and use a check against "this" to prevent self assignment.
Edit: Let me try to take a broader view, which might be more useful to you.
In Java, objects are implicitly passed around by reference and not by value, and they are garbage collected also, automatically destroyed when no-one needs them anymore.
The closest way to get that kind of semantics in C++ is to pass around std::shared_ptr<A> when in java you would have passed A. Then, when you need to compare against this, you can use the get method to get a raw pointer from the shared pointer and compare it literally against this. OR, if you use the std::enable_shared_from_this template when you define your class, you can use shared_from_this to get a shared_ptr<A> to this at any point in your member functions, and compare the shared_ptr's directly.
I'm assuming you are using C++11, otherwise you would use boost headers for that stuff.
Note also the stuff about "weak_ptr" which you might need to use if you have cyclic references.
That's because this is a pointer type in C++. If your function signature would use a pointer as well, it would work:
object::doOperation(object* a)
{
if(a != this)
{
set(a);
}
doOperation();
}
In Java most objects are passed around as references. To avoid aliasing problems you may then need to check for reference equality: are these two apparently distinct objects, really distinct, or do the references refer to the same object?
In C++ objects are often passed as values, copying their values. And for values it doesn't make sense to check for object identity. E.g. a function argument passed by value, as in your object::doOperation(object a) example, will always have an address different from everything else at that point in the program execution (it's freshly allocated).
Still there are some cases where objects are passed by reference (or pointer), and where self-check is appropriate.
For example, a copy assignment operator might go like this:
auto My_class::operator=( My_class const& other )
-> My_class&
{
if( &other != this )
{
values_ = other.values_; // Avoid this work for self-assign.
}
return *this;
}
The self-check can also be crucial for correctness, although with use of standard library containers and smart pointers correctness can usually be ensured without any self-check.
If an object has been passed by value as in
void object::doSomething(object x)
{
// whatever
}
then it is not necessary to compare with this. Even of the caller does
some_object.doSomething(some_object);
the x is a temporary copy - i.e. so a different object is guaranteed.
If the argument is passed by reference or argument then remember that this is a pointer and not a reference (unlike Java in which those concepts are entwined), for example;
void object::doSomething(object *x)
{
if (this != x)
{
}
}
and
void object::doSomething(object &x)
{
if (this != &x)
{
}
}
The latter assumes that object does not have an interfering operator&(). If that assumption is invalid then, in C++11 use addressof(x) (where addressof() is specified in <memory>. Before C++11, the tricks to get address of x are a little more indirect (e.g. a sequence of casts).
Personally, I don't do such tests at all. Instead, I simply do
void object::doSomething(object &x)
{
object temp(x);
// do things with temp and *this
std::swap(x, temp);
}
which relies on working copy semantics, but also gives more exception safety. If a class makes the above prohibitive, then that is more usually a problem with class design (better to find another way to avoid the need to compare with this).
Related
I have a library defining method() that returns type V* and can return nullptr. What's the best way to wrap that method to turn the value into a std::optional<V>?
The naive way would be something like:
std::optional<V> maybe_value;
V* value = method();
if (value != nullptr) {
maybe_value = *value; // assuming the type is even copyable
}
But I was hoping there'd already be some STL function I could use to do this as a one-liner wrapper around method().
Your way looks basically fine to me, and is roughly what I'd do. You don't want a one-liner here as it would not be very clear. Ultimately you can create a function for it if you like.
One concern: be very careful with ownership semantics here. Who owns *value? Can it be copied? Is that meaningful? Can you move it instead? Who frees the original object?
Always ask these questions when passed a pointer, even if it appeared that the pointer was only chosen in order to add nullability.
To be quite honest, although std::optional is preferable in new code (or code you're refactoring), I'm not convinced that wrapping a function like this is worth the potential confusion, not to mention the cost of a copy (if, indeed, that is necessary).
There is no such function. Assignment of any value makes the optional containing a value. But you can provide your own
template <typename T>
std::optional<T*> optional_ptr(T* ptr) {
return ptr ? std::optional<T*>(ptr) : std::optional<T*>();
}
Consider the following scenario: There is a class CDriver that is in charge of enumerating all the attached output devices (represented by the COutput class). The code for that may look something like this:
class COutput
{
// COutput stuff
};
class CDriver
{
public:
CDriver(); // enumerate outputs and store in m_outputs
// some other methods
private:
std::vector<COutput> m_outputs;
};
Now CDriver should be able to grant the user access to the enumerated COutputs.
The first method of achieving this is to return a pointer:
const COutput* GetOutput(unsigned int idx) const
{
return idx < m_outputs.size() ? &m_outputs[idx] : nullptr;
}
The way I see it, this method presents the problem that if the pointer is stored by the user and it persists after the CDriver object has been destroyed, it is now a dangling pointer. This is due to the fact that the pointee (COutput object) has been destroyed during the destructor of the CDriver object.
The second way of doing this would be to return by reference:
const COutput& GetOutput(unsigned int idx) const
{
return idx < m_outputs.size() ? &m_outputs[idx] : m_invalidOutput;
}
Here the same problems apply as in the approach with pointers. Furthermore it has the additional caveat that no real invalid object can be returned. If a nullptr is returned as a return pointer, it is obvious that it is "invalid". There is, however, no equivalent to nullptr when it comes to references.
Moving on to approach number three. Return by value.
COutput GetOutput(unsigned int idx) const
{
return idx < m_outputs.size() ? &m_outputs[idx] : m_invalidOutput;
}
Here, the user doesn't have to worry about the lifetime of the returned object. However, the COutput object has to be copied and there is, similary to the reference approach, no intuitive way to check for errors.
I could go on...
For example, the COutput objects could be allocated on the heap and stored in std::shared_ptrs and returned as such. This, however would make the code very verbose.
Is there any way to solve this problem intuitively and without introducing unnecessary code verbosity?
Let me start off by saying, you should absolutely not start messing around with shared_ptr to solve this problem. Just don't do it. You have a few different options here that are reasonable.
First, you can simply return by value. If COutput is small, this is a good way to go. To deal with an out of bounds index, you have two options. One is throw an exception. Works well and is easy. This is what I would recommend here most likely. Make sure to have a size() member that the user can call to get the size, so they can avoid paying the cost of throwing, if that is too expensive for them. You can also return an optional. This is in the standard library as of 17, in boost prior, and there are standalone implementations.
Second, you can return by pointer/reference. Yes, it can dangle. But C++ does not claim to offer protection against this. Every single standard container features begin() and end() methods that return iterators can easily dangle as well. Expecting clients to avoid these pitfalls is not unreasonable in C++ (you should of course document them though).
Third, you can do inversion of control: instead of giving the user an object to operate on, you instead make the user pass in the action they want to take. In other words:
template <class F>
auto apply(std::size_t idx, F f) const
{
if (idx >= m_outputs.size())
{
throw std::out_of_range("index is out of range");
}
return f(m_outputs[idx]);
}
Usage:
CDriver x;
x.apply(3, [] (const COutput& o) {
o.do_something();
});
The user needs to work quite a bit harder to make something dangle in this case (though it's still possible) since they aren't handed a pointer/reference, and you don't have to make a copy either.
You can of course change apply in many ways; e.g. not return back from the functional call but instead return true/false to indicate whether the index was in range instead of throwing. The basic idea is the same. Note that this approach would have to be modified to be used in conjunction with virtual functions, which would make it less desirable. So if you are thinking of polymorphism for CDriver, you should consider that.
Take a look at C++11's shared pointers. With shared pointers, the base object's deconstructor won't be called until all shared pointers "owning" that object are destroyed. This removes a lot (but not all) of the headache when dealing with multiple references to a single object.
Here's some more info:
http://en.cppreference.com/w/cpp/memory/shared_ptr
1). The tried and tested: throw a standard argument exception
2) You could use tuples and std::tie.
const std::tuple<bool, COutput> GetOutput(unsigned int idx) const
{
return idx < m_outputs.size()
? std::make_tuple(true m_outputs[idx])
: std::make_tuple(false, m_invalidOutput);
}
bool has_value;
COutput output;
std::tie(has_value, output) = GetOutput(3);
To replace tuples and std::tie in C++17 structured bindings can be used.
3) C++17 will have std::optional for this kind of scenario.
I have functions of the following form in the code I'm refactoring:
A f()
{
if(existing)
return A();
else
return A(handle);
}
The Safe Bool Idiom is later used to test if A is associated with a handle or not, i.e. if we should call the class methods for this object which require internally a valid handle for execution. A's methods are const.
I'd like to return an interface, IA, here instead. Must I therefore return a pointer? If so I will go with boost shared pointers. I can test if the pointer is pointing to something or not.
Is there any way for me to work with references here instead? Would you recommend such an approach or do you think that boost::shared_ptrs is the way to go?
UPDATE
A is derived from IA.
My compiler is gcc version 4.4.3.
My biggest problem with this code is that A is used to interact with an external C API. Therefore I wish to mock it away using the IA interface as base for my Mock of A and its implementation, A. Then outside of the method f() above, which I see as a factory, I will only work with IA pointers. Dependency Injection in other words.
So A is basically a handle and an interface to a set of C API functions which require a handle. I can have several objects of type A where the interface is the same but the handle is different.
I'd return a std::unique_ptr< AI > object :
std::unique_ptr< AI > f()
{
if(existing)
return std::unique_ptr< AI >( new A() );
else
return std::unique_ptr< AI >( new A(handle) );
}
In the above case, the slicing doesn't happen, and the compiler will move* the object.
* I assumed you are using the c++11.
Since you are not using c++11, the simplest is to use boost::shared_ptrs :
boost::shared_ptrs< AI > f()
{
if(existing)
return boost::shared_ptrs< AI >( new A() );
else
return boost::shared_ptrs< AI >( new A(handle) );
}
In such case, you do not have to take care whether and when the created object gets destructed. The boost::shared_ptrs will take care of that.
I'd go with pointers too, but you can also work with references:
A& f()
{
if(existing)
{
static A a;
return a;
}
else
{
static A a(handle);
return a;
}
}
You are fully aware of the implications though, right? i.e. you can't re-assign the reference and modifying it means modifying the local static variable.
From your code snippet it seems that you are constructing A objects in function f. In such a case, returning the object by value is probably the best thing you can do. The compiler will use return value optimization (RVO) and optimize all the copies away.
Check this article by Dave Abrahams on passing and returning objects by value.
Be aware that this solution will not work if you are returning a base class of A, due to the slicing problem. If returning an A object is fine, then this is probably the best solution.
If you can understand pointers then work with pointers. If you can't, then stay with what you've got. Looks like the guy before you did his best to avoid pointers. As betabandido said, the compiler will make best out of it, even if it seems slow - on paper.
Interface is a design pattern to take fullest advantage of pointers. It doesn't make very much sense without pointers and casting.
To test if the pointer is pointing at something or not, there is NULL value. No need to roll out cannons if you're shooting flies.
Explain why you're not comfortable with the code as it is now. Maybe the problem isn't really severe.
Returning a pointer is one way to go.
To me, another simple and native way is to add a return value to the method's signature.
int f(A & a)
{
if(existing)
{
return ERROR_ALREADY_EXISTS;
}
else
{
A temp(handle);
a = temp;
return SUCCEEDED;
}
}
I am programming in C++ more then 5 years, and have never met any place where reference of the variable is recommended to use except as a function argument (if you don't want to copy what you pass as your function argument). So could someone point cases where C++ variable reference is recommended (I mean it gives any advantage) to use.
As a return value of an opaque collection accessor/mutator
The operator[] of std::map returns a reference.
To shorten the text needed to reference a variable
If you miss old-school with Foo do ... statement (that's Pascal syntax), you can write
MyString &name = a->very->long_->accessor->to->member;
if (name.upcase() == "JOHN") {
name += " Smith";
}
another example of this can be found in Mike Dunlavey's answer
To state that something is just a reference
References are also useful in wrapper objects and functors--i.e. in intermediate objects that logically contact no members but only references to them.
Example:
class User_Filter{
std::list<User> const& stop_list;
public: Functor (std::list<User> const& lst)
: stop_list(lst) { }
public: bool operator()(User const& u) const
{ return stop_list.exists(u); }
};
find_if(x.begin(),x.end(),User_Filter(user_list));
The idea here that it's a compile error if you don't initialize a reference in constructor of such an object. The more checks in compile time--the better programs are.
Here's a case where it's handy:
MyClass myArray[N];
for (int i = 0; i < N; i++){
MyClass& a = myArray[i];
// in code here, use a instead of myArray[i], i.e.
a.Member = Value;
}
Use references wherever you want, pointers when you are forced to.
References and pointers share part of their semantics: they are an alias to an element that is not present. The main difference is with memory managements: references express clearly that you are not responsible for the resource. On the other hand, with pointers it is never really clear (unless you mean smart pointers): are you assumed to delete the pointer or will it be deleted externally?
You must use pointers when you must manage memory, want to allow for optional semantics or need to change the element referred to at a later time.
In the rest of cases, where you can use a reference or a pointer, references are clearer and should be preferred.
Now, as you point out, they are really not needed: you can always use pointers for all the reference uses (even parameter passing), but the fact that you can use a single tool for everything does not mean there are no better suited tools for the job.
I tend to use reference members instead of pointers for externally controlled non-optional construction parameters.
EDIT (added example):
Let's say that you have a database and a DAO class having the database as a dependency:
struct Database {};
struct PersonDao {
const Database &m_d;
PersonDao(const Database &d): m_d(d) {}
};
Furthermore, the scope of the database is controlled externally from the DAO:
int main() {
Database d;
PersonDao pd(d);
}
In this case it makes sense to use a reference type, since you don't ever want DAO::m_d to be null, and its lifetime is controlled externally (from the main function in this case).
I use references in function arguments not just to avoid copies but also instead of pointers to avoid having to deal with NULL pointers where appropriate. Pointers model a "maybe there's a value, but maybe not (NULL)", references are a clear statement that a value is required.
... and to make it absolutely clear (-> comments). I tend to avoid pointers to model "maybe there are several values" - a vector is a better option here. Pointers to several values often end up in C-style programming because you usually have to pass the # of elements as well separately.
Use a const reference to give a name to a value, e.g.:
const Vec3 &ba=b-a;
This names the value, but doesn't necessarily create a variable for it. In theory, this gives the compiler more leeway and may allow it to avoid some copy constructor calls.
(Related non-duplicated Stack Overflow question at Const reference to temporary. The Herb Sutter link there has more information about this.)
The argument to the copy-constructor MUST be passed as a reference, since otherwise the copy constructor would need to call it self in an endless recursion (stack overflow).
I tend to agree, but perhaps const return values.
Well you kind of have two choices for aliasing other values(ignoring shared_ptrs and the like): pointers and references.
References must be initialized at construction to refer to something else. So semantically a reference can never be NULL. In reality, though, the underlying data can go away, giving you problems often more difficult to debug than if a pointer went away. So I'm not sure there's a real advantage here unless you were disciplined and consistent with how they were used vis-a-vis referring to items that were dynamically allocated. If you did this with pointers too, you'd avoid the same problems.
Perhaps more importantly, references can be used without thinking about all the issues that arise with pointers. This is probably the main advantage. Semantically a reference is the thing. If you guarantee as the caller/callee that the underlying memory doesn't go away, you don't have to confuse the user with any of the questions that come along with pointers (Do I need to free this? Could this be NULL? etc) and can safely use a reference for convenience.
An example of this might be a function that looks up the corresponding string for an enum,
const std::string& ConvertToString( someEnum val)
{
static std::vector< std::string > lookupTable;
if (lookupTable.empty())
{
// fill in lookup table
}
// ignoring the cast that would need to happen
return lookupTable[val]
}
Here the contract between the caller and the callee guarantees that the return type will always be there. You can safely return a reference, and avoid some of the questions that pointers invite.
References make code prettier. So use them whenever it takes a reference to beautify your code.
i would like to enlist some cases:
1) while writing singleton classes
class singleton
{
singleton();
explicit singleton(const singleton&);
singleton& operator=(const singleton&);
public:
static singleton& instance()
{
static singleton inst;
return inst;
}
};// this is called the 'Meyers' singleton pattern. refer to More Effective C++ by Scott Meyers
it has all the benefits, but avoids using the new operator
**2)**here is no such thing as a null reference. A reference must always refer to some object. As a result, if you have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, you should make the variable a pointer, because then you can set it to null. On the other hand, if the variable must always refer to an object, i.e., if your design does not allow for the possibility that the variable is null, you should probably make the variable a reference
**3)**Because a reference must refer to an object, C++ requires that references be initialized:
string& rs; // error! References must
// be initialized
string s("xyzzy");
string& rs = s; // okay, rs refers to s
Pointers are subject to no such restriction
The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it
**4)**Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, always refers to the object with which it is initialized: ¤ Item M1, P10
string s1("Nancy");
string s2("Clancy");
string& rs = s1; // rs refers to s1
string *ps = &s1; // ps points to s1
rs = s2; // rs still refers to s1,
// but s1's value is now
// "Clancy"
ps = &s2; // ps now points to s2;
// s1 is unchanged
Stream operators are an obvious example
std::ostream & operator<< (std::ostream &, MyClass const &...) {
....
}
mystream << myClassVariable;
You obviously don't want a pointer as checking for NULL makes using an operator very tedious i.s.o. convenient
I've used a reference to an ostream instead of a pointer. I supppose that I prefer references to pointers when the class has a lot of operators.
What's a good existing class/design pattern for multi-stage construction/initialization of an object in C++?
I have a class with some data members which should be initialized in different points in the program's flow, so their initialization has to be delayed. For example one argument can be read from a file and another from the network.
Currently I am using boost::optional for the delayed construction of the data members, but it's bothering me that optional is semantically different than delay-constructed.
What I need reminds features of boost::bind and lambda partial function application, and using these libraries I can probably design multi-stage construction - but I prefer using existing, tested classes. (Or maybe there's another multi-stage construction pattern which I am not familiar with).
The key issue is whether or not you should distinguish completely populated objects from incompletely populated objects at the type level. If you decide not to make a distinction, then just use boost::optional or similar as you are doing: this makes it easy to get coding quickly. OTOH you can't get the compiler to enforce the requirement that a particular function requires a completely populated object; you need to perform run-time checking of fields each time.
Parameter-group Types
If you do distinguish completely populated objects from incompletely populated objects at the type level, you can enforce the requirement that a function be passed a complete object. To do this I would suggest creating a corresponding type XParams for each relevant type X. XParams has boost::optional members and setter functions for each parameter that can be set after initial construction. Then you can force X to have only one (non-copy) constructor, that takes an XParams as its sole argument and checks that each necessary parameter has been set inside that XParams object. (Not sure if this pattern has a name -- anybody like to edit this to fill us in?)
"Partial Object" Types
This works wonderfully if you don't really have to do anything with the object before it is completely populated (perhaps other than trivial stuff like get the field values back). If you do have to sometimes treat an incompletely populated X like a "full" X, you can instead make X derive from a type XPartial, which contains all the logic, plus protected virtual methods for performing precondition tests that test whether all necessary fields are populated. Then if X ensures that it can only ever be constructed in a completely-populated state, it can override those protected methods with trivial checks that always return true:
class XPartial {
optional<string> name_;
public:
void setName(string x) { name_.reset(x); } // Can add getters and/or ctors
string makeGreeting(string title) {
if (checkMakeGreeting_()) { // Is it safe?
return string("Hello, ") + title + " " + *name_;
} else {
throw domain_error("ZOINKS"); // Or similar
}
}
bool isComplete() const { return checkMakeGreeting_(); } // All tests here
protected:
virtual bool checkMakeGreeting_() const { return name_; } // Populated?
};
class X : public XPartial {
X(); // Forbid default-construction; or, you could supply a "full" ctor
public:
explicit X(XPartial const& x) : XPartial(x) { // Avoid implicit conversion
if (!x.isComplete()) throw domain_error("ZOINKS");
}
X& operator=(XPartial const& x) {
if (!x.isComplete()) throw domain_error("ZOINKS");
return static_cast<X&>(XPartial::operator=(x));
}
protected:
virtual bool checkMakeGreeting_() { return true; } // No checking needed!
};
Although it might seem the inheritance here is "back to front", doing it this way means that an X can safely be supplied anywhere an XPartial& is asked for, so this approach obeys the Liskov Substitution Principle. This means that a function can use a parameter type of X& to indicate it needs a complete X object, or XPartial& to indicate it can handle partially populated objects -- in which case either an XPartial object or a full X can be passed.
Originally I had isComplete() as protected, but found this didn't work since X's copy ctor and assignment operator must call this function on their XPartial& argument, and they don't have sufficient access. On reflection, it makes more sense to publically expose this functionality.
I must be missing something here - I do this kind of thing all the time. It's very common to have objects that are big and/or not needed by a class in all circumstances. So create them dynamically!
struct Big {
char a[1000000];
};
class A {
public:
A() : big(0) {}
~A() { delete big; }
void f() {
makebig();
big->a[42] = 66;
}
private:
Big * big;
void makebig() {
if ( ! big ) {
big = new Big;
}
}
};
I don't see the need for anything fancier than that, except that makebig() should probably be const (and maybe inline), and the Big pointer should probably be mutable. And of course A must be able to construct Big, which may in other cases mean caching the contained class's constructor parameters. You will also need to decide on a copying/assignment policy - I'd probably forbid both for this kind of class.
I don't know of any patterns to deal with this specific issue. It's a tricky design question, and one somewhat unique to languages like C++. Another issue is that the answer to this question is closely tied to your individual (or corporate) coding style.
I would use pointers for these members, and when they need to be constructed, allocate them at the same time. You can use auto_ptr for these, and check against NULL to see if they are initialized. (I think of pointers are a built-in "optional" type in C/C++/Java, there are other languages where NULL is not a valid pointer).
One issue as a matter of style is that you may be relying on your constructors to do too much work. When I'm coding OO, I have the constructors do just enough work to get the object in a consistent state. For example, if I have an Image class and I want to read from a file, I could do this:
image = new Image("unicorn.jpeg"); /* I'm not fond of this style */
or, I could do this:
image = new Image(); /* I like this better */
image->read("unicorn.jpeg");
It can get difficult to reason about how a C++ program works if the constructors have a lot of code in them, especially if you ask the question, "what happens if a constructor fails?" This is the main benefit of moving code out of the constructors.
I would have more to say, but I don't know what you're trying to do with delayed construction.
Edit: I remembered that there is a (somewhat perverse) way to call a constructor on an object at any arbitrary time. Here is an example:
class Counter {
public:
Counter(int &cref) : c(cref) { }
void incr(int x) { c += x; }
private:
int &c;
};
void dontTryThisAtHome() {
int i = 0, j = 0;
Counter c(i); // Call constructor first time on c
c.incr(5); // now i = 5
new(&c) Counter(j); // Call the constructor AGAIN on c
c.incr(3); // now j = 3
}
Note that doing something as reckless as this might earn you the scorn of your fellow programmers, unless you've got solid reasons for using this technique. This also doesn't delay the constructor, just lets you call it again later.
Using boost.optional looks like a good solution for some use cases. I haven't played much with it so I can't comment much. One thing I keep in mind when dealing with such functionality is whether I can use overloaded constructors instead of default and copy constructors.
When I need such functionality I would just use a pointer to the type of the necessary field like this:
public:
MyClass() : field_(0) { } // constructor, additional initializers and code omitted
~MyClass() {
if (field_)
delete field_; // free the constructed object only if initialized
}
...
private:
...
field_type* field_;
next, instead of using the pointer I would access the field through the following method:
private:
...
field_type& field() {
if (!field_)
field_ = new field_type(...);
return field_;
}
I have omitted const-access semantics
The easiest way I know is similar to the technique suggested by Dietrich Epp, except it allows you to truly delay the construction of an object until a moment of your choosing.
Basically: reserve the object using malloc instead of new (thereby bypassing the constructor), then call the overloaded new operator when you truly want to construct the object via placement new.
Example:
Object *x = (Object *) malloc(sizeof(Object));
//Use the object member items here. Be careful: no constructors have been called!
//This means you can assign values to ints, structs, etc... but nested objects can wreak havoc!
//Now we want to call the constructor of the object
new(x) Object(params);
//However, you must remember to also manually call the destructor!
x.~Object();
free(x);
//Note: if you're the malloc and new calls in your development stack
//store in the same heap, you can just call delete(x) instead of the
//destructor followed by free, but the above is the correct way of
//doing it
Personally, the only time I've ever used this syntax was when I had to use a custom C-based allocator for C++ objects. As Dietrich suggests, you should question whether you really, truly must delay the constructor call. The base constructor should perform the bare minimum to get your object into a serviceable state, whilst other overloaded constructors may perform more work as needed.
I don't know if there's a formal pattern for this. In places where I've seen it, we called it "lazy", "demand" or "on demand".