C++ persistence of objects declared within a block, memory leakage possibility? - c++

First of all let me prefix this question with the following points:
1) I have searched Stackexchange for this issue, most of the code presented was difficult enough for me to follow in order to warrant Asking a new Question/Opening a new Thread about this. The closest i could find was this Creating multiple class objects with the same name? c++ and unfortunately this is way past my scope of understanding
2) http://www.cplusplus.com/doc/tutorial/classes/ has not really discussed this or i have missed it.
Now that this is out of the way:
Rectangle Class code:
class Rectangle {
private:
int lineNumber;
float valueMax;
float valueMin;
public:
Rectangle(SCStudyInterfaceRef sc, int lineNumber, float valueMax, float valueMin);
int getLineNumber(); // member function of class
float getValueMax(); // member function of class Rectangle
float getValueMin(); // member function of class Rectangle
};
Rectangle::Rectangle(SCStudyInterfaceRef sc, int lineNumber0, float value1, float value2) {
lineNumber = lineNumber0;
int value2_greater_than_value1 = sc.FormattedEvaluate(value2, sc.BaseGraphValueFormat, GREATER_OPERATOR, value1, sc.BaseGraphValueFormat);
if (value2_greater_than_value1 == 1) {
valueMax = value2;
valueMin = value1;
} else {
valueMax = value1;
valueMin = value2;
}
}
int Rectangle::getLineNumber() {
return lineNumber;
}
float Rectangle::getValueMax() {
return valueMax;
}
float Rectangle::getValueMin() {
return valueMin;
}
And here is the more important part, this code is running pretty much in a loop and will repeat everytime a certain event triggers it:
bool xxx = Conditions here
if (xxx) {
// Draw new rectangle using plattforms code
code here
// Save rectangle information in the list:
Rectangle rect(sc, linenumbr + indexvalue, high, low);
(*p_LowRectanglesList).push_back(rect);
}
bool yyy = conditions here
if (Short) {
// Draw new rectangle using plattforms code
code here
// Save rectangle information in the list:
Rectangle rect(sc, linenumber + indexvalue, high, low);
(*p_HighRectanglesList).push_back(rect);
}
So the question is the following:
Since this is looped everytime an event triggers the second part of the code is going to be run, the bool condition is going to be checked, if its true its going to use plattform integrated code to draw a rectangle. Once it has drawn it this information is going to be passed to a new rectangle object/instance based on the Rectangle Class in the first part of the code using the: Rectangle rect(sc, linenumber + indexvalue, high, low); part and then save that information in a list which is in a different part of the code for now and irrelevant.
What exactly happens when there is a new Bool = True condition and the code gets executed after it has already been executed? Will the old rectangle object be simply replaced with a new rectangle object with the same name and using the new parameters (since they change on every instance due to the way the code is written)? Or are there now two objects of the Rectangle Class using the same name "rect" ?
It's technically speaking not even that important to me since the information of the parameters should be pushed into a list anyways using the (*p_HighRectanglesList).push_back(rect); part of the code
So TL;DR:
Does "rect" get destroyed/overwritten or are there now potentially limitless amounts of Rectangle Objects/Instances called "rect" floating around?
My Apologies for the wall of text but being a complete noob i thought it would be best to outline my thought process so that it will be easier for you to correct me on where I'm wrong.
Kind regards,
Orbital

Yes, rect is destroyed and recreated every loop. In C++, the scope of any variable declared in a block (in this case an if() statement) is limited to that block. Every time your program iterates, you get a new rect, and the old rect is gone.

To add, whenever you call NEW, you are basically allocating memory and creating Rectangle objects. NEW will allocate address to each instance. The pointer *rect will be pointing to the current memory address, and when you call rect with NEW again, now rect will be pointing to the new memory address the previous address becomes a NULL reference. However in C++ you have to worry about memory leaks unlike Java where you have a garbage collector.

Related

C++ Using classes in other classes failing

I have a Display class that uses SDL to write pixels to the screen. I'd like another class (Triangle) to be able to use this already existent class object, so I've been trying to pass the object by address.
It's sort of working, in the sense that it is actually calling the methods. However, I was getting a segmentation fault in the DrawPixel function. After checking gdb and checking what values are in the function, I figured out that the color_buffer array does not exist (note that when DrawPixel is called directly from the display class in main it works fine).
After a little more testing, I determined that window_width, window_height etc are not set in the Triangle's version of the Display object. But they do exist in the original Display object.
So I'm assuming that I am not properly passing in my object, but I'm uncertain how to fix this issue as I thought passing by address would work just fine. How can I pass an already existing/instantiated class to another class?
I've also tried putting color_buffer into public variables in case private was causing it, but that didn't help.
Example:
main.cpp
int main() {
Display display;
Triangle triangle(&display);
// This doesn't work
triangle.DrawTriangle(300, 500, 0xFFFFFF00);
// This does work
display.DrawPixel(300, 500, 0xFFFFFF00);
return 0;
}
triangle.hpp
class Triangle {
private:
Display* display;
public:
DrawTriangle(int x, int y, uint32_t color);
};
triangle.cpp
Triangle::Triangle(Display* display) {
display=display;
}
Triangle::DrawTriangle(int x, int y, uint32_t color) {
display->DrawPixel(x, y, color);
}
display.hpp
class Display {
private:
// SDL Stuff defined here
uint32_t* color_buffer;
int window_width = 1920;
int window_height = 1080;
public:
Display();
DrawPixel(int x, int y, uint32_t color);
};
display.cpp
Display::Display() {
// SDL Stuff declared
color_buffer = new uint32_t[window_width * window_height];
}
Display::DrawPixel(int x, int y, uint32_t color) {
// This is receiving the correct values, but doesn't allow me to access
// any index of color_buffer.
color_buffer[(y * window_width) + x] = color;
}
Triangle::Triangle(Display* display) {
display=display;
}
the display is not the member of your class.Use this->display = display instead
You have to use "this" in Triangle constructor. That should solve the problem.
Triangle(Display* display) {
this->display=display;
}
A couple of things to add to the answers above:
use a different naming convention for member variables - this way it is very easy to avoid typos. _display, m_display, Display_ (Clang style =) )
class members are private by default so if you are following convention where attributes are defined on top, there's no need to add private:
Some prefer references (e.g. Display&), mostly to save typing ->, since if `Display goes out of scope it will have the same hilarious effect as passing a pointer.
static analyzers look down on pointer arithmetic(due to possible out-of-bounds writes).
You can use std::array from header:
static constexpr int WIDTH = 1920;
static constexpr int HEIGHT = 1080;
std::array<uint32_t, WIDTH* HEIGHT> m_color_buffer{};
and then either use m_color_buffer[index] = color (no bounds checking, random memory gets written if you write out of bounds in release and normally an exception in debug), or use m_color_buffer.at(index) - slower but this way you get an exception in release mode, but the compiler may complain about the stack size, as the definition is essentially the same as uint32_t buffer[WIDTH*HEIGHT]. std::vector is a better alternative - it hides buffer allocation, manages memory (no need to delete) at expense of the 2 extra pointers for begin and the end of the vector.
The code example lacked a destructor. Every new should have an accompanying delete hence either add it or just switch to a standard library container to avoid the headache =)
Last but not least - both classes override constructors. Display also manages resources. What happens when you copy Display instances? Move them? It is a bit of a headache and leads to a bit of a boilerplate, but it is best to implement Rule of 5 members and avoid accidental surprises =)
PS. C++ is a beautiful language =)

Class method being called in main, changes don't persist outside class method?

Basically, I have two classes, Peg and Disk. (It's a Towers of Hanoi program) The files I have are Disk.h, Disk.cpp, Peg.h, Peg.cpp, and main.cpp. Not sure if that matters. Here's the disk class from Disk.h
#include <vector>
#include "gwindow.h"
#ifndef DISK_H
#define DISK_H
class Disk
{
private:
int xCoord; //x and y coords are for drawing in a gwindow
int yCoord;
int mHeight;
int mWidth;
COLOR mColor;
int mName; //helps me keep track of which is which
public:
Disk(); //default constructor
Disk(int x, int y, int heightIn, int widthIn, COLOR colorIn);
void setXY(int x, int y); //this is the one I'm having trouble with
int getHeight();
int getWidth();
int getX();
int getY();
COLOR getColor();
std::string diskColor();
void draw(GWindow &gw);
void nameDisk(int name); //yet this one is working?
int getName();
};
#endif
However, I'm having trouble with the setXY function. When I call it from main, it calls the function properly, changes the variable inside the scope of setXY, but the value doesn't persist outside the function. However, nameDisk works fine and is basically the same thing, except it is changing mName instead of xCoord and yCoord. Here is setXY:
void Disk::setXY(int x, int y)
{
xCoord = x;
yCoord= y;
}
and here is how I call it from main:
pegVec[2].getDisks()[0].setXY(690, 200);
I know this looks crazy, but basically pegVec is a vector of 3 peg objects. Each peg object has a function, getDisks(), which returns a vector of all the disks on that peg currently. So the line above is trying to perform setXY on the first peg on peg 2. Sorry if that's unclear, but I've tried making a new disk object and calling it on that and that didn't work either.
Here is getDisks, if it matters:
std::vector<Disk> Peg::getDisks()
{
return disksOn;
}
and disksOn is just a member variable of Peg:
std::vector<Disk> disksOn;
I think it might be a problem with how getDisks() works. I'm a noob, but I'm guessing that returning the vector disksOn makes a "copy" of it, kind of, which is what I am altering with my setXY function but which is not the same as the actual disksOn vector associated with the Peg object? I don't know if that makes sense.
What I've tried so far:
Making xCoord and yCoord public variables and updating them manually instead of making a setter function. This did not work.
I printed out the x and y values at every step. Inside setXY, the values were updated successfully, but when the function ended they went back to how they were.
I tried some mess with the const keyword, but I don't understand it and couldn't even get it to run.
Passing everything by reference/value
Making a new function in main which accepted a Disk vector as input, and using getDisks as input to that function. Didn't work, same problems.
Tested my other setter function, nameDisk, which works fine. It's essentially the same as setXY, which is why I think the problem is with getDisks.
Using pointers at various points (heh) throughout, but I wasn't sure the best way to do that. I was messing with it last night so I don't remember 100% but I think I tried to have getDisks return a pointer instead of the vector, and I don't think that worked, but it's more likely a problem with my syntax and how I used the pointer. I think that might work but I don't know how to shake it.
Help?
You're on the right track - somehow you're looking at a different objects than what you think you are. Using references is a good solution, but you may not have got the right one ;-)
Try:
// Return reference to the disks on the peg.
std::vector<Disk>& Peg::getDisks()
{
return disksOn;
}
The issue is that
std::vector<Disk> getDisks() { return disksOn; }
returns a completely new and separate temporary copy of disksOn rather than a reference to the original. So you're modifying a temporary copy which gets discarded at the end of the statement.
You need to use
std::vector<Disk> &getDisks() { return disksOn; } in order to return a reference to disksOn.
Although if you are going to return a reference to the vector member object you might as well make the object directly accessible as public because anyone can manipulate the vector at this point and get rid of the getDisks() function as it serves no purpose in terms of access protection.
Better design would be to give access to individual disks:
Disk &getDisk(int index) {
return disksOn[index];
}
const Disk &getDisk(int index) const {
return disksOn[index];
}
The idea behind not giving direct access to the vector is that you can later change the underlying container type if needed without changing the code outside of the Peg class.
The second version (const) is necessary for accessing const Disks of const Peg objects.

How to create method which will know that its instance is in matrix of another class

I'm an absolute beginner in OOP (and C++). Trying to teach myself using resources my university offers for students of higher years, and a bunch of internet stuff I can find to clear things up.
I know basic things about OOP - I get the whole point of abstracting stuff into classes and using them to create objects, I know how inheritance works (at least, probably the basics), I know how to create operator functions (although as far as I can see that only helps in code readability in a sense that it becomes more standard, more language like), templates, and stuff like that.
So I've tried my first "project": to code Minesweeper (in command line, I never created a GUI before). Took me a few hours to create the program, and it works as desired, but I feel like I'm missing a huge point of OOP in there.
I've got a class "Field" with two attributes, a Boolean mine and a character forShow. I've defined the default constructor for it to initialize an instance as an empty field (mine is false), and forShowis . (indicating a not yet opened filed). I've got some simple inline functions such as isMine, addMine, removeMine, setForShow, getForShow, etc.
Then I've got the class Minesweeper. Its attributes are numberOfColumns, ~ofRows, numberOfMines, a pointer ptrGrid of type Mine*, and numberOfOpenedFields. I've got some obvious methods such as generateGrid, printGrid, printMines (for testing purposes).
The main thingy about it is a function openFiled which writes the number of mines surrounding the opened field, and another function clickField which recursively calls itself for surrounding fields if the field which is currently being opened has 0 neighbor mines. However, those two functions take an argument -- the index of the field in question. That kinda misses the point of OOP, if I understand it correctly.
For example, to call the function for the field right to the current one, I have to call it with argument i+1. The moment I noticed this, I wanted to make a function in my Field class which would return a pointer to the number right to it... but for the class Field itself, there is no matrix, so I can't do it!
Is it even possible to do it, is it too hard for my current knowledge? Or is there another more OOP-ish way to implement it?
TLDR version:
It's a noob's implemetation of Minesweeper game using C++. I got a class Minesweeper and Field. Minesweeper has a pointer to matrix of Fields, but the navigation through fields (going one up, down, wherever) doesn't seem OOP-ishly.
I want to do something like the following:
game->(ptrMatrix + i)->field.down().open(); // this
game->(ptrMatrix + i + game.numberOfColumns).open(); // instead of this
game->(ptrMatrix + i)->field.up().right().open(); // this
game->(ptrMatrix + i + 1 - game.numberOfColumns).open(); // instead of this
There are a couple of ways that you could do this in an OOP-ish manner. #Peter Schneider has provided one such way: have each cell know about its neighbours.
The real root of the problem is that you're using a dictionary (mapping exact coordinates to objects), when you want both dictionary-style lookups as well as neighbouring lookups. I personally wouldn't use "plain" OOP in this situation, I'd use templates.
/* Wrapper class. Instead of passing around (x,y) pairs everywhere as two
separate arguments, make this into a single index. */
class Position {
private:
int m_x, m_y;
public:
Position(int x, int y) : m_x(x), m_y(y) {}
// Getters and setters -- what could possibly be more OOPy?
int x() const { return m_x; }
int y() const { return m_y; }
};
// Stubbed, but these are the objects that we're querying for.
class Field {
public:
// don't have to use an operator here, in fact you probably shouldn't . . .
// ... I just did it because I felt like it. No justification here, move along.
operator Position() const {
// ... however you want to get the position
// Probably want the Fields to "know" their own location.
return Position(-1,-1);
}
};
// This is another kind of query. For obvious reasons, we want to be able to query for
// fields by Position (the user clicked on some grid), but we also would like to look
// things up by relative position (is the cell to the lower left revealed/a mine?)
// This represents a Position with respect to a new origin (a Field).
class RelativePosition {
private:
Field *m_to;
int m_xd, m_yd;
public:
RelativePosition(Field *to, int xd, int yd) : m_to(to), m_xd(xd),
m_yd(yd) {}
Field *to() const { return m_to; }
int xd() const { return m_xd; }
int yd() const { return m_yd; }
};
// The ultimate storage/owner of all Fields, that will be manipulated externally by
// querying its contents.
class Minefield {
private:
Field **m_field;
public:
Minefield(int w, int h) {
m_field = new Field*[w];
for(int x = 0; x < w; x ++) {
m_field[w] = new Field[h];
}
}
~Minefield() {
// cleanup
}
Field *get(int x, int y) const {
// TODO: check bounds etc.
// NOTE: equivalent to &m_field[x][y], but cleaner IMO.
return m_field[x] + y;
}
};
// The Query class! This is where the interesting stuff happens.
class Query {
public:
// Generic function that will be instantiated in a bit.
template<typename Param>
static Field *lookup(const Minefield &field, const Param &param);
};
// This one's straightforwards . . .
template<>
Field *Query::lookup<Position>(const Minefield &field, const Position &pos) {
return field.get(pos.x(), pos.y());
}
// This one, on the other hand, needs some precomputation.
template<>
Field *Query::lookup<RelativePosition>(const Minefield &field,
const RelativePosition &pos) {
Position base = *pos.to();
return field.get(
base.x() + pos.xd(),
base.y() + pos.yd());
}
int main() {
Minefield field(5,5);
Field *f1 = Query::lookup(field, Position(1,1));
Field *f0 = Query::lookup(field, RelativePosition(f1, -1, -1));
return 0;
}
There are a couple of reasons why you might want to do it this way, even if it is complicated.
Decoupling the whole "get by position" idea from the "get neighbour" idea. As mentioned, these are fundamentally different, so expose a different interface.
Doing it in this manner gives you the opportunity to expand later with more Query types in a straightforwards fashion.
You get the advantage of being able to "store" a Query for later use. Perhaps to be executed in a different thread if it's a really expensive query, or in an event loop to be processed after other events, or . . . lots of reasons why you might want to do this.
You end up with something like this: (C++11 ahead, be warned!)
std::function<Field *()> f = std::bind(Query::lookup<RelativePosition>,
field, RelativePosition(f1, -1, -1));
. . . wait, what?
Well, what we essentially want to do here is "delay" an execution of Query::lookup(field, RelativePosition(f1, -1, -1)) for later. Or, rather, we want to "set up" such a call, but not actually execute it.
Let's start with f. What is f? Well, by staring at the type signature, it appears to be a function of some sort, with signature Field *(). How can a variable be a function? Well, it's actually more like a function pointer. (There are good reasons why not to call it a function pointer, but that's getting ahead of ourselves here.)
In fact, f can be assigned to anything that, when called, produces a Field * -- not just a function. If you overload the operator () on a class, that's a perfectly valid thing for it to accept as well.
Why do we want to produce a Field * with no arguments? Well, that's an execution of the query, isn't it? But the function Query::lookup<RelativePosition> takes two arguments, right?
That's where std::bind comes in. std::bind essentially takes an n-argument function and turns it into an m-argument function, with m <= n. So the std::bind call takes in a two-place function (in this case), and then fixes its first two arguments, leaving us with . . .
. . . a zero-argument function, that returns a Field *.
And so we can pass around this "function pointer" to a different thread to be executed there, store it for later use, or even just repeatedly call it for kicks, and if the Position of Fields was to magically change for some reason (not applicable in this situation), the result of calling f() will dynamically update.
So now that I've turned a 2D array lookup into a mess of templates . . . we have to ask a question: is it worth it? I know this is a learning exercise and all, but my response: sometimes, an array is really just an array.
You can link the four neighbours to the cell via pointers or references. That would likely happen after the playing field has been created. Whether that's good or bad design I'm not sure (I see the same charme though that you see). For large fields it would increase the memory footprint substantially, because a cell probably doesn't hold that much data besides these pointers:
class Cell
{
// "real" data
Cell *left, *right, *upper, *lower;
// and diagonals? Perhaps name them N, NE, E, SE, S...
};
void init()
{
// allocate etc...
// pseudo code
foreach r: row
{
foreach c: column
{
// bounds check ok
cells[r][c].upper = &cells[r-1][c];
cells[r][c].left = &cells[r][c-1];
// etc.
}
}
// other stuff
}

std::vector::push_back fails to add data to my vector

I have these two pieces of code that are messing up without throwing any errors:
The first piece is from a custom class which I am trying to push into an array.
class idRect {
public:
sf::FloatRect rect;
int id;
idRect(int _id, sf::FloatRect _rect) : id(_id), rect(_rect) {}
};
The second piece is where the function gets called.
if((deltaX + deltaY) < 500) { //Taxi distance calculation
cout << endl << "Passed check" << endl;
gloAreas.push_back(idRect(id, entity.getGlobalBounds()));
}
gloAreas is a globally defined vector which contains idRect objects.
As said earlier I have observed from the console that "Passed check" outputs and that the size of my vector doesn't increase EDIT: globally.
Edit: The error also seems rather random and only happens for 1 in 6 instances of the objects calling the push_back functions.
I'm using SFML for the sf::FloatRect which is basically just a vector of 4 floats. getGlobalBounds() is another function from SFML that returns the bounding rectangle of a sprite in sf::FloatRect format.
Any ideas of what is going wrong?
Sincerely,
BarrensZeppelin
EDIT 2:
The error seems to have erupted due to a mix between my own incompetence and std::multiset's sorting, maybe I'll come back for that in another thread ^^ (With a sscce ofc)
Thank you guys for you time and help.
If gloAreas is defined as static, it won't be a true global. It will have global scope, but a copy of it will be created for each translation unit.
For a global, you need to declare it with extern and define it in a single implementation file.
Disclaimer: answer is just a guess, my crystal ball might be off today...
My crystal ball answer: You have redefined gloAreas in an interior scope, like this:
vector<idRect> gloAreas; // defines global
void F( vector<idRect> gloAreas ) // defines local instance
{
gloAreas.push_back(); // affects local instance
return; // destroys local instance
}
int main() {
F(gloAreas); // Copies global instance to parameter
// global remains unchanged.
}

Why is `this` equal to 0x0, causing my program to crash?

I'm designing a simple Connect 4 game. So far, I have 4 underlying classes:
Colour - responsible for representing colours (RGBA). Includes conversion operators.
Player - represents a player of the game. Each Player has a Colour and a name.
Board - represents the playing board. It contains dimensions, as well as a 2D vector of Tiles with those dimensions.
Tile - a nested class within Board. Represents one space on the board. Each Tile has a Colour and an std::unique_ptr to the owner of that tile. The owner starts as nullptr and can be changed once to a Player. The colour starts as a transparent black.
I've tested my Colour class and it appears to be working fine. My Player class is in tip-top shape as well. However, I'm having some problems with the Board/Tile classes.
My test consisted of creating two players, and a board. These executed normally. Next, I loop through the dimensions of the board, once for each tile. I then call
board.tile (j, i).claimBy (p2);
The loop goes through rows with i and columns with j, the way you'd expect to print it.
tile (j, i) retrieves the tile I'm working with. It works as expected.
Chain of Events Leading to the Crash:
claimBy (p2) sets the tile to become claimed by player 2. It is implemented as follows:
bool Board::Tile::claimBy (const Player &owner)
{
if (!_owner)
{
*_owner = owner;
_colour = owner.colour();
return true;
}
return false;
}
_owner is my std::unique_ptr<Player>. It first checks whether the owner of the tile has been set before (i.e. is not nullptr). If not, it sets the Player inside to the one passed in. It then updates the tile's colour and returns true. If the tile has been previously claimed, it returns false.
Following the debugger, the crash occurs in the line *_owner = owner;. Stepping in takes me to the line struct Player (my declaration of the Player class), which I take to be the implicit copy constructor (remember the class only has a Colour _colour and a std::string _name).
Stepping in again leads me to Colour::operator= (which makes sense for a copy constructor to call). Here's the definition:
Colour &Colour::operator= (const Colour &rhs)
{
if (*this != rhs)
{
_red = rhs.red();
_green = rhs.green();
_blue = rhs.blue();
_alpha = rhs.alpha();
}
return *this;
}
The path turns into *this != rhs. This is just a reverse call to operator==, which is:
return red() == rhs.red()
&& green() == rhs.green()
&& blue() == rhs.blue()
&& alpha() == rhs.alpha();
The first comparison here red() == rhs.red() has red() which is just return _red;. This is the point at which the program crashes. The debugger states that this (this->_red) is 0x0.
I'm clueless about why this is happening. My best guess is that I'm using the smart pointer wrongly. I've never actually used one before, but it should be pretty similar to normal pointers, and I didn't think release would accomplish anything if the pointer is nullptr.
What could be the cause of this being 0x0?
Edit:
I'm sure everything is initialized, as I do so in each constructor, in member initializers (e.g. Board::Tile::Tile() : _colour (Colours::NONE), _owner (nullptr){}), where NONE is a transparent black.
I'm also not too proficient with a debugger, as I haven't used it that much over printing debugging values.
The line
*_owner = owner;
means "make a copy of the owner object, and store it at the place that _owner points to." The problem is that _owner doesn't point to anything yet; it's still null.
If you really want to make a copy of the Player object in each tile that the player controls, you'd need to do
_owner.reset(new Player(owner));
But making copies of the Player object is a strange thing to do. Consider using shared_ptr instead — you can have both owner and _owner be shared_ptrs, and just assign one to the other in the usual way.
You start off with a default initialized std::unique_ptr<Player>. That is to say, the equivalent of a NULL pointer with some cleanup semantics. Then you try to dereference it in the statement *_owner=owner; so that you can assign to it.
Thus the statement *_owner=owner; is basically equivalent to ((Player*)NULL)->operator=(owner);, calling the implicit assignment operator. The first thing this does is then equivalent to ((Player*)NULL)->_colour=owner._colour; Finding this==NULL is not surprising here; indeed, it's expected.
The fix depends on what you actually want to happen. Should each Board::Tile be given a completely new copy of its owner? Then you want to instead say _owner.reset(new Player(owner)). Do you just want each tile to hold a reference to an already existing player? Can you guarantee that the Player object owner will outlive the Board::Tile object? Then you want a raw pointer: (in declaration of Board::Tile) Player const *_owner; (in implementation) _owner=&owner;.