The program crash. I'm trying to implement a Brick ** create_bricks()
function that return a pointer to pointer of Brick (because I want to create an array of Bricks and return the position of the first). I'm pulling my hair out and the last thing I do after several try and fails, erros and research, was to simplify my code and check value of the pointers line by line. When I dereference the_brick
as *the_brick
in the draw function game loop it doesn't get the same value as the one that new Brick()
assign to ptr_brick
inside create_bricks()
function. I'm using SFML, but the problems is about pointers.
Note : If I return a Brick *
from create_bricks
with proper modifications it works fine (and draw the brick), but I need to create multiple bricks, no only one.
#include "Brick.h"
int main()
{
...
while (window.isOpen())
{
Brick ** ptr_bricks = create_bricks();
Brick * ptr_brick = *ptr_bricks;
window.draw(*the_brick);
}
return 0;
}
Brick ** create_bricks()
{
Brick * ptr_brick = new Brick();
ptrBrick->setPosition(150, 20);
return &ptrBrick;
}
#include "Brick.h"
Brick::Brick()
{
LOG(INFO) << "Brick constructor";
setPosition(10, 10);
setSize(sf::Vector2f(100, 20));
setFillColor(sf::Color::Green);
setOutlineThickness(1);
}
Brick::~Brick()
{
LOG(INFO) << "Brick destructor";
//dtor
}
Thanks
The problem is the return
statement in the create_bricks
function:
return &ptrBrick;
Here you return a pointer to the local variable ptrBrick
. The life-time of this variable will end when the function ends, and any pointer you have to it will become invalid as soon as the function ends.
The natural C++ solution to return an "array" from a function is to return a std::vector
instead:
std::vector<Brick*> create_bricks()
{
Brick* brick = new Brick;
brick->setPosition(150, 20);
return { brick };
}
If Brick
is not a polymorphic class you don't even need to use a vector of pointer, but a vector of plain Brick
objects ( std::vector<Brick>
).
If you persist in using pointers you must allocate an array of pointers to Brick
, which means new Brick*[number_of_bricks]
(or new Brick[number_of_bricks]
if polymorphism isn't needed).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.