Reputation: 582
I've the following definitions
class Expression {
public:
virtual int evaluate() const = 0;
virtual std::string to_string() const = 0;
};
class Constant : public Expression {
int value;
public:
Constant() = delete;
Constant(int value) : value(value) {}
Constant(Constant&& c) = default;
virtual int evaluate() const { return value; }
virtual std::string to_string() const { return std::to_string(value); }
};
class BinaryOperator : public Expression {
protected:
const Expression& leftOperand;
const Expression& rightOperand;
public:
BinaryOperator() = delete;
BinaryOperator(const Expression& left, const Expression& right)
: leftOperand{left}, rightOperand{right} {}
BinaryOperator(Expression&& left, Expression&& right) // (2)
: leftOperand(std::move(left)), rightOperand(std::move(right)) {}
virtual std::string to_string() const = 0;
};
class PlusOperator : public BinaryOperator {
public:
using BinaryOperator::BinaryOperator;
virtual int evaluate() const {
return leftOperand.evaluate() + rightOperand.evaluate();
}
virtual std::string to_string() const {
return "(" + leftOperand.to_string() + "+" + rightOperand.to_string() + ")";
}
};
and this main function
int main(void) {
Constant c1{5}, c2{10};
PlusOperator p1{c1, c2};
std::cout << p1.to_string() << " = " << p1.evaluate() << std::endl;
PlusOperator p2{Constant{5}, Constant{10}};
std::cout << p2.to_string() << " = " << p2.evaluate() << std::endl; // (1)
}
There is no problem during compiling (g++ -std=c++17
). However, if I use the -fsanitize=address
flag to compile, the program dies at the point (1). According to gdb when I want to call p2.to_string()
. I assume, that I am doing something wrong at (2) and the object is not properly stored/lifetime extended.
So my concrete questions are: how is it possible to bind a temporary object to my Expression-Ref without failing the address-sanitizer? What are alternatives?
Thanks in advance!
Upvotes: 0
Views: 69
Reputation: 180630
So my concrete question is: how is it possible to bind a temporary object to my Expression-Ref without failing the address-sanitizer?
You can't. Temporaries are destroyed at then end of the full expression, unless you capture them with a function local reference to const or function local rvalue reference. You class members aren't function local references to const or function local rvalue references, so there is no temporary lifetime extension.
Upvotes: 1