@CGunn86, In the first post of the thread, it appears (edited since then) you asked a vague question returning unique_ptr not working and didn't fully explain the use-case. You didn't explain, for example, why you chose unique_ptr. So tpb, grasping at straws, took some time to come up with a concrete example of a working unique_ptr return.
You then replied a bunch of code that doesn't make sense, because, let's be honest -- you just made it up. While tpb's answer might've been a bit on the rude side, I, too, might be a bit offended by your impulsive reply -- what language are you even trying to write in that has capital "Class" , capital "Public:", capital "Private:", and then random Paddle constructor + destructor inside the Game class?
I highly suggest you try one of the online compilers like
http://repl.it/languages/cpp to formulate "why doesn't this work?" code snippets. That would immediately reduce the 'whiteboarding' errors, at least.
But yeah, about the topic itself -- you'd benefit from explaining whether you're trying to return new Paddle objects each time and transfer ownership to the user. Perhaps you only wanted to give them read-only access to an existing Paddle and don't need null checks, in which case a const ref may be enough.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
#include <memory>
using namespace std;
struct Paddle
{
Paddle(int val) : val(val)
{
}
int val;
};
class Game
{
public:
Game() :
left_paddle_(Paddle(42)),
right_paddle_(new Paddle(50))
{
}
const Paddle& LeftPaddle() { return left_paddle_; }
shared_ptr<const Paddle> RightPaddle() { return right_paddle_; }
shared_ptr<Paddle> NullPaddle() { return null_paddle_; }
private:
Paddle left_paddle_;
shared_ptr<Paddle> right_paddle_;
shared_ptr<Paddle> null_paddle_;
};
int main()
{
Game g;
cout << boolalpha;
cout << "LeftPaddle value: " << g.LeftPaddle().val << endl;
//g.LeftPaddle().val = 31; // error: assignment of member 'Paddle::val' in read-only object
cout << "RightPaddle is null? " << (g.RightPaddle() == nullptr) << endl;
//g.RightPaddle()->val = 33; // error: assignment of member 'Paddle::val' in read-only object
cout << " rightpaddle value: "<<g.RightPaddle()->val << endl;
cout << "NullPaddle is null? "<< (g.NullPaddle() == nullptr) << endl;
}
|
https://repl.it/repls/MajesticInformalMacrolanguage
LeftPaddle value: 42
RightPaddle is null? false
rightpaddle value: 50
NullPaddle is null? true |