Tag Info

Hot answers tagged

9

Firstly, you probably shouldn't implement a container class. 95% of the time you should one included in the standard library. If you just want to learn, or are in the 5%, carry on. If you are defining a template, leave the decision up to your users. You users can use: Stack<Foo> if they want by value. Stack<Foo*> if they want by pointer. ...


6

C++11 introduced two new utility classes: std::shared_ptr and std::unique_ptr. If you need to control a resource through multiple handles, then wrap it in a std::shared_ptr, which is a reference-counted smart pointer that cleans up the resource when there are no more pointers to it. std::unique_ptr is designed for single ownership, but it too will ...


3

My question is: what is the preferred approach in C++? Is there a preferred approach? Which approach should I normally take when implementing 'container' classes? In C++ you can keep objects by: value reference pointer smart pointer (std::unique_ptr, std::shared_ptr, YourPointerClass). (you didn't mention the last two). Each of these is valid for ...


2

To extend on comments, your assertion On some platforms references have to be at least 64 bit, so it cannot rely on usually atomic 32 bit word operations is not quite correct. Yes, on some platforms your references will be 64 bit, but that's (universally?) because their word size is 64 bit. After all, if the word size didn't match your address size, ...


2

To start off your code is broken. Returning a reference or the address of a local variable is returning garbage. Never do this. Here I've rewritten your example to return something real. int xByAdress = 20; int xByReference = 30; int* returnByAdress() { return &xByAdress; } int& returnByReference() { return xByReference; } int main() { ...


2

Preparing my flame-retardant suit, as I feel some bias must be present in any answer to this question. First, I would like to note that I work within the embedded world, so RAII and stack allocation are generally the way to go. In almost any circumstance, I see passing something in by reference as a good idea because of the obvious reason: it can't be NULL. ...


1

If I'm writing code on the client side, I don't know which of the variables I pass to a function might be changed and which I can expect to remain the same without an explicit knowledge of the parent function declaration. This is as it should be. When you call an API, you should know what you are calling and why. You should also know what the function ...


1

No, they are not the same bars, since you are calling new. Also I don't see $bars being used anywhere in wireFoosAndBars. Use the exact "associated" instances from $bars when constructing the new collection and they will be the same objects. You are correct in that clone is the only way to make a copy of an object. Modifying an object's properties, no ...



Only top voted, non community-wiki answers of a minimum length are eligible